1. #include<iostream>
  2. using namespace std;
  3.  
  4. // Exchange two doubles
  5. void exchange(double& x, double& y)
  6. {
  7. double t = x;
  8. x = y;
  9. y = t;
  10. }
  11.  
  12. // Rearrange the elements of the array so that all the elements
  13. // whose value is > divider come before all the other elements,
  14. // and all the elements whose value is < divider come after all
  15. // the other elements. Upon return, firstNotGreater is set to the
  16. // index of the first element in the rearranged array that is
  17. // <= divider, or n if there is no such element, and firstLess is
  18. // set to the index of the first element that is < divider, or n
  19. // if there is no such element.
  20. // In other words, upon return from the function, the array is a
  21. // permutation of its original value such that
  22. // * for 0 <= i < firstNotGreater, a[i] > divider
  23. // * for firstNotGreater <= i < firstLess, a[i] == divider
  24. // * for firstLess <= i < n, a[i] < divider
  25. // All the elements > divider end up in no particular order.
  26. // All the elements < divider end up in no particular order.
  27. void divide(double a[], int n, double divider,
  28. int& firstNotGreater, int& firstLess)
  29. {
  30. if (n < 0)
  31. n = 0;
  32.  
  33. // It will always be the case that just before evaluating the loop
  34. // condition:
  35. // firstNotGreater <= firstUnknown and firstUnknown <= firstLess
  36. // Every element earlier than position firstNotGreater is > divider
  37. // Every element from position firstNotGreater to firstUnknown-1 is
  38. // == divider
  39. // Every element from firstUnknown to firstLess-1 is not known yet
  40. // Every element at position firstLess or later is < divider
  41.  
  42. firstNotGreater = 0;
  43. firstLess = n;
  44. int firstUnknown = 0;
  45. while (firstUnknown < firstLess)
  46. {
  47. if (a[firstUnknown] < divider)
  48. {
  49. firstLess--;
  50. exchange(a[firstUnknown], a[firstLess]);
  51. }
  52. else
  53. {
  54. if (a[firstUnknown] > divider)
  55. {
  56. exchange(a[firstNotGreater], a[firstUnknown]);
  57. firstNotGreater++;
  58. }
  59. firstUnknown++;
  60. }
  61. }
  62. }
  63.  
  64. // Rearrange the elements of the array so that
  65. // a[0] >= a[1] >= a[2] >= ... >= a[n-2] >= a[n-1]
  66. // If n <= 1, do nothing.
  67. void order(double a[], int n)
  68. {
  69. if (n <= 1)
  70. return;
  71.  
  72. // Divide using a[0] as the divider (any element would do).
  73. int firstNotGreater;
  74. int firstLess;
  75. divide(a, n, a[0], firstNotGreater, firstLess);
  76.  
  77. // sort the elements > divider
  78. order(a, firstNotGreater);
  79.  
  80. // sort the elements < divider
  81. order(a+firstLess, n-firstLess);
  82. }
  83.  
  84. int main()
  85. {
  86. int a[10] = {1,1,3,2,4,5,7,0,4,9};
  87. order(a,10);
  88. for(int i = 0; i < 10; i++)
  89. cout << a[i] << endl;
  90. }