Advertisement
geoBadita

Untitled

Jun 25th, 2020
551
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. /**
  2.  * Function to perform the quicksort partition - Theta(right-left)
  3.  * @param a - array to be partitioned
  4.  * @param left - left index
  5.  * @param right - right index
  6.  * @result p - index in a such that all elements a0..ap-1 <= ap and all elements ap+1..an-1 >= ap
  7.  */
  8. int partition(int a[], int left, int right) {
  9.     int pivot = a[right];
  10.     int i = left - 1;
  11.  
  12.     for (int j = left; j < right; j++) {
  13.         if (a[j] < pivot) {
  14.             i++;
  15.             int tmp = a[i];
  16.             a[i] = a[j];
  17.             a[j] = tmp;
  18.         }
  19.     }
  20.     int tmp = a[i + 1];
  21.     a[i + 1] = a[right];
  22.     a[right] = tmp;
  23.  
  24.     return i + 1;
  25. }
  26.  
  27. /**
  28.  * Function to sort a list using quicksort - complexity O(n^2) - avg Theta(nlogn)
  29.  * @param a - list to be sorted
  30.  * @param left - left index
  31.  * @param right - right index
  32.  * @result a permutation of list a such that (a0 <= a1 <=...<= an-1)
  33.  */
  34. void quickSortAux(int a[], int left, int right) {
  35.     if (left < right) {
  36.         int p = partition(a, left, right);
  37.         quickSortAux(a, left, p - 1);
  38.         quickSortAux(a, p + 1, right);
  39.     }
  40. }
  41.  
  42. /**
  43.  * Function to sort a list using quicksort - complexity O(n^2) - avg Theta(nlogn)
  44.  * @param a - list to be sorted
  45.  * @param n - length of the list
  46.  * @result a permutation of list a such that (a0 <= a1 <=...<= an-1)
  47.  */
  48. void quickSort(int a[], int n) {
  49.     quickSortAux(a, 0, n - 1);
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement