fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // using Lomuto partition scheme
  5. int Partition(int a[], int start, int end)
  6. {
  7. // Pick rightmost element as pivot from the array
  8. int pivot = a[end];
  9.  
  10. // elements less than pivot will be pushed to the left of pIndex
  11. // elements more than pivot will be pushed to the right of pIndex
  12. // equal elements can go either way
  13. int pIndex = start;
  14.  
  15. // each time we finds an element less than or equal to pivot, pIndex
  16. // is incremented and that element would be placed before the pivot.
  17. for (int i = start; i < end; i++)
  18. {
  19. if (a[i] <= pivot)
  20. {
  21. swap(a[i], a[pIndex]);
  22. pIndex++;
  23. }
  24. }
  25. // swap pIndex with Pivot
  26. swap (a[pIndex], a[end]);
  27.  
  28. // return pIndex (index of pivot element)
  29. return pIndex;
  30. }
  31.  
  32.  
  33. // using randomized partition
  34. int RandomizedPartition(int a[], int start, int end)
  35. {
  36. // choose a random index between [start, end]
  37. int pivotIndex = rand() % (end - start + 1) + start;
  38.  
  39. // swap the end element with element present at random index
  40. swap(a[pivotIndex], a[end]);
  41.  
  42. // call partition procedure
  43. return Partition(a, start, end);
  44. }
  45.  
  46. // Quicksort routine
  47. void QuickSort(int a[] ,int start, int end)
  48. {
  49. // base condition
  50. if(start >= end)
  51. return;
  52.  
  53. // rearrange the elements across pivot
  54. int pivot = RandomizedPartition(a, start, end);
  55.  
  56. // recurse on sub-array containing elements that are less than pivot
  57. QuickSort(a, start, pivot - 1);
  58.  
  59. // recurse on sub-array containing elements that are more than pivot
  60. QuickSort(a, pivot + 1, end);
  61. }
  62.  
  63. int main()
  64. {
  65. int a[] = { 9, -3, 5, 2, 6, 8, -6, 1, 3 };
  66. int n = sizeof(a)/sizeof(a[0]);
  67.  
  68. QuickSort(a, 0, n - 1);
  69.  
  70. // print the sorted array
  71. for (int i = 0 ; i < n; i++)
  72. cout << a[i] << " ";
  73. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
-6 -3 1 2 3 5 6 8 9