jkhsjdhjs

Array Sort O(n) (not for every array)

Jun 14th, 2016
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. /*
  2.  *Aufgabe H19
  3.  * a) Das Programm ließt eine Datei Zeile für Zeile ein, speichert sich immer den höchsten Wert und schreibt die Anzahl der Zeilen mit.
  4.  *    Die Zeilenzahl entspricht der Variable m und der Höchstwert ist n.
  5.  *    Die Funktion sort() bekommt dann m und n übergeben und baut daraus das Array neu auf und gibt es zurück, anschließend wird es in die Datei out.txt geschrieben.
  6.  *    Das Programm überprüft NICHT ob das Eingabearray im richtigen Format war, weil dies meiner Meinung nach nicht in O(m) Schritten möglich ist.
  7.  *    Dafür "sortiert" das Programm das Array aber in O(n) Schritten und verwendet nur konstant viel Speicher zusätzlich nur Eingabe.
  8.  *
  9.  * b) array1.txt 0s
  10.  *    array2.txt 0s
  11.  *    array3.txt 0.003s
  12.  *    array4.txt 0.04s
  13.  *    array5.txt 0.512s
  14. */
  15.  
  16.  
  17.  
  18. #include "stdafx.h"
  19. #include <iostream>
  20. #include <conio.h>
  21. #include <fstream>
  22. #include <string>
  23. #include <ctime>
  24.  
  25. using namespace std;
  26.  
  27. int* sort(int m, int n) {
  28.     int* a = new int[m]{0};
  29.     for (int i = 0; i < n; i++) {
  30.         a[i + m - n] = i + 1;
  31.     }
  32.     return a;
  33. }
  34.  
  35.  
  36. int main(int argc, char** argv) {
  37.     if (argc <= 1) {
  38.         cout << "Error! No file specified!" << endl;
  39.         _getch();
  40.         return 1;
  41.     }
  42.     int lines{0}, max{0};
  43.     string line;
  44.     ifstream in(argv[1]);
  45.     cout << "Reading file..." << endl;
  46.     while (getline(in, line)) {
  47.         if (atoi(line.c_str()) >= max) {
  48.             max = atoi(line.c_str());
  49.         }
  50.         lines++;
  51.     }
  52.     in.close();
  53.     cout << "Sorting...";
  54.     clock_t begin = clock();
  55.     int* a = sort(lines, max);
  56.     clock_t end = clock();
  57.     double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
  58.     cout << " " << elapsed_secs << "s" << endl;
  59.     cout << "Writing out.txt..." << endl;
  60.     ofstream out("out.txt");
  61.     for (int i = 0; i < lines; i++) {
  62.         out << a[i] << endl;
  63.     }
  64.     out.close();
  65.     cout << "Done!" << endl;
  66.     _getch();
  67.     return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment