Sc3ric

quicksort-for-humans

Feb 27th, 2023 (edited)
730
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 KB | None | 0 0
  1. int partition(vector<int>& a, int start, int end, int& comparisons, int& swaps)
  2. {
  3.     int pivot = a[end];
  4.     int i = start;
  5.     int j = start;
  6.     while (i < end) {
  7.         comparisons++;
  8.         if (a[i] > pivot) {
  9.             i++;
  10.         }
  11.         else {
  12.             if (i != j) {
  13.                 swaps++;
  14.                 swap(&a[i], &a[j]);
  15.             }
  16.             i++;
  17.             j++;
  18.         }
  19.     }
  20.     if (i != j) {
  21.         swaps++;
  22.         swap(&a[i], &a[j]);
  23.     }
  24.     i++;
  25.     j++;
  26.     return j - 1;
  27. }
  28.  
  29. void quickReq(vector<int>& a, int start, int end, int& comparisons, int& swaps)
  30. {
  31.     if (start < end)
  32.     {
  33.         int p = partition(a, start, end, comparisons, swaps);
  34.         quickReq(a, start, p - 1, comparisons, swaps);
  35.         quickReq(a, p + 1, end, comparisons, swaps);
  36.     }
  37. }
  38.  
  39. vector<int> QuickSort(vector<int> a, int& comparisons, int& swaps) {
  40.     int n = a.size();
  41.     comparisons = 0;
  42.     swaps = 0; 
  43.  
  44.     quickReq(a, 0, n-1, comparisons, swaps);
  45.  
  46.     return a;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment