Advertisement
baadgeorge

trpo

Nov 12th, 2021
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1. #include<iostream>
  2. #include<vector>
  3. #include<fstream>
  4. #include<string>
  5. #include<sstream>
  6.  
  7. using namespace std;
  8.  
  9. template <typename T>
  10. int partition(vector<T>& V, int low, int high){
  11.     T pivot = V[floor((high + low)/2)];
  12.  
  13.     int i = low;
  14.     int j = high;
  15.     while (true) {
  16.  
  17.         while (V[i] < pivot) {
  18.             i++;
  19.         }
  20.  
  21.         while (V[j] > pivot) {
  22.             j--;
  23.         }
  24.  
  25.         if (i >= j) return j;
  26.  
  27.         swap(V[i++], V[j--]);
  28.     }
  29. }
  30.  
  31. template <typename T>
  32. void quicksort(vector<T> &V, int low, int high){
  33.  
  34.     if (low < high)
  35.     {
  36.         T pivot = partition(V, low, high);
  37.  
  38.         quicksort(V, low, pivot);
  39.         quicksort(V, pivot+1, high);
  40.     }
  41.     return;
  42. }
  43.  
  44. bool isNumber(const string& str) {
  45.     return str.find_first_not_of("-.,0123456789") == string::npos;
  46. }
  47.  
  48. template <typename T>
  49. string parsStream(vector<T>& V, ifstream& input ) {
  50.  
  51.     string delimiter = " ";
  52.     string token;
  53.     T buf;
  54.  
  55.     while (getline(input, token, ' ')) {
  56.         if (isNumber(token))
  57.         {
  58.             stringstream string_s(token);
  59.             string_s >> buf;
  60.             V.push_back(buf);
  61.         }
  62.  
  63.         else return token;
  64.     }
  65.     return "";
  66. }
  67.  
  68. template <typename T>
  69. void printSequence(const vector<T>& V) {
  70.     for (int i = 0; i < V.size(); i++) {
  71.         cout << V[i] << " ";
  72.     }
  73.     cout << endl;
  74.    
  75. }
  76.  
  77.  
  78.  
  79.  
  80. int main() {
  81.    
  82.     ifstream FILE;
  83.     //vector<int> V = { 12,3,4,5,6,78,0 };
  84.    
  85.     vector<int> V;
  86.  
  87.     string buf;
  88.  
  89.     FILE.open("input.txt");
  90.  
  91.     buf = parsStream(V, FILE);
  92.  
  93.     FILE.close();
  94.  
  95.     if (V.size() == 0) {
  96.         cout << "File contains no elements" << endl;
  97.         return -1;
  98.     }
  99.  
  100.     if (buf != "") {
  101.         cout << "File contains characters other than numbers: " << buf << endl;
  102.         return -1;
  103.     }
  104.  
  105.     cout << "Unsorted sequence from file" << endl;
  106.     printSequence(V);
  107.  
  108.     quicksort(V, 0, V.size()-1);
  109.  
  110.     cout << "Sorted sequence from file" << endl;
  111.     printSequence(V);
  112.  
  113.     return 0;
  114. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement