1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
#include <iostream>
int main()
{
int A[] = {5, 9, 12, 15, 0, 1, 5, 10};
const int SIZE = sizeof(A)/sizeof(A[0]);
Quick_Sort(A, 0, SIZE-1); // call with SIZE-1
for(int i : A) std::cout << i << " ";
std::cout << "\n";
}
void Quick_Sort(int A[], int p, int r)
{
if(p < r)
{
int q = Partition(A, p, r);
Quick_Sort(A, p, q-1);
Quick_Sort(A, q+1, r);
}
}
int Partition(int A[], int p, int r)
{
int x = A[r]; // pivot is last element
int i = p-1;
for(int j = p; j < r; j++) // go up to second-to-last element
{
if(A[j] <= x)
{
i++;
std::swap(A[j], A[i]);
}
}
std::swap(A[i+1], A[r]); // swap with last element
return i+1;
}
|