#include <vector>
#include <iostream>
#include <algorithm>
#include <Windows.h>
using namespace std;
// QuickSort(List A)
// if A size <= 1
// return
// pick A[i] from A as pivot
// (L, M, R) <- partition-3way(A, i)
// QuickSort(List L)
// QuickSort(List R)
int partitionAtLast(vector<int> &arry, int start, int end)
{
// choose the last element as pivot
int i = start;
for (int j = start; j <= end - 2; ++j)
if (arry[j] <= arry[end - 1])
swap(arry[i++], arry[j]);
swap(arry[i], arry[end - 1]);
return i;
}
void SimpleHelper(vector<int> &arry, int start, int end)
{
if (start < end)
{
int pivot = partitionAtLast(arry, start, end);
SimpleHelper(arry, start, pivot);
SimpleHelper(arry, pivot + 1, end);
}
}
// average case: O(nlog(n))
// the simple quick sort will degrade to O(n*n) if the array is sorted already
void quickSort_Simple(vector<int> &arry)
{
SimpleHelper(arry, 0, arry.size());
}
void RandomizedHelper(vector<int> &arry, int start, int end)
{
int i = start;
int j = end - 1;
int sz = end - start;
int pivot;
if (sz > 1)
{
pivot = rand() % sz + start;
while (true)
{
while (arry[j] > arry[pivot] && j >= pivot)
--j;
while (arry[i] < arry[pivot] && i <= pivot)
++i;
if (i >= j)
break;
swap(arry[i], arry[j]);
}
}
else
return;
RandomizedHelper(arry, start, pivot);
RandomizedHelper(arry, pivot + 1, end);
}
void quickSort_Randomized(vector<int> &arry)
{
RandomizedHelper(arry, 0, arry.size());
}
void printArray(const vector<int> &arry)
{
for (int i = 0; i < arry.size(); cout << arry[i++] << " ");
cout << endl;
}
int main()
{
vector<int> arry{ 1, 8, 3, 5, 11, 9, 39, 21 };
printArray(arry);
quickSort_Randomized(arry);
printArray(arry);
system("PAUSE");
return 0;
}
Reference:
http://www.cs.cmu.edu/~avrim/451f11/lectures/lect0906.pdf
http://www.cs.princeton.edu/~wayne/kleinberg-tardos/pdf/05DivideAndConquerI.pdf