Advertisement
Guest User

Untitled

a guest
Dec 5th, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.72 KB | None | 0 0
  1. int partition(vector<int>& v, int piv, int low, int high) {
  2.     int i = low-1;
  3.     int j = high+1;
  4.     while (low <= high) {
  5.         do { i++; } while(v[i] < piv);
  6.         do { j--; } while(v[j] > piv);
  7.         if (i >= j) return j;
  8.         swap(v[i], v[j]);
  9.     }
  10. }
  11.  
  12. int pivot(vector<int>& v, int l, int h) {
  13.     int a = v[l];
  14.     int b = v[(l+h)/2];
  15.     int c = v[h];
  16.     if ((a <= b && b <= c) || (a >= b && b >= c)) return b;
  17.     else if ((a <= c && c <= b) || (a >= c && c >= b)) return c;
  18.     else return a;
  19. }
  20.  
  21. void insertionsort(vector<int>& v) {
  22.     for (int i = 1; i < v.size(); ++i) {
  23.         int j = i;
  24.         while (j > 0 && v[j-1] > v[j]) {
  25.             swap(v[j-1], v[j]);
  26.             j--;
  27.         }
  28.     }
  29. }
  30.  
  31. void quicksort(vector<int>& v, int low, int high) {
  32.     if (low < high) {
  33.         if (v.size() < 150) {
  34.             insertionsort(v);
  35.             return;
  36.         }
  37.         int piv = pivot(v, low, high);
  38.         int p = partition(v, piv, low, high);
  39.         quicksort(v, low, p);
  40.         quicksort(v, p+1, high);
  41.     }
  42. }
  43.  
  44. int main() {
  45.     vector<int> v;
  46.     // bool b = true;
  47.     // while (b) {
  48.     //     int n;
  49.     //     cin >> n;
  50.     //     if (n == 0) break;
  51.     //     v.push_back(n);
  52.     // }
  53.     srand(time(0));
  54.     for (int i = 0; i < 100000; ++i) {
  55.         int x = rand();
  56.         v.push_back(x);
  57.     }
  58.     // for (int i : v) cout << i << " ";
  59.     // cout << "\n";
  60.     auto start = high_resolution_clock::now();
  61.     quicksort(v, 0, v.size()-1);
  62.     auto stop = high_resolution_clock::now();
  63.     // for (int i : v) cout << i << " ";
  64.     // cout << "\n";
  65.     auto duration = duration_cast<microseconds>(stop-start);
  66.     cout << "time: " << duration.count() << "\n";
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement