期望时间复杂度为O(nlgn)
#include<iostream>
#include<vector>
using namespace std;
int Partition(vector<int> &A, int p, int r)
{
int i,j;
int key,temp;
i = p - 1;
key = A[r]; //The key set A[r] value
for (j = p; j <= r; j++)
{
if (A[j] < key)
{
i += 1;
temp = A[j];
A[j] = A[i];
A[i] = temp;
}
}
temp = A[r];
A[r] = A[i + 1];
A[i + 1] = temp;
return i + 1;
}
void QuickSort(vector<int> &A, int p, int r)
{
int q;
if (p < r)
{
q = Partition(A, p, r);
QuickSort(A, p, q - 1);
QuickSort(A, q + 1, r);
}
}
int main(void)
{
vector<int> A = { 2, 8, 7, 1, 3, 5, 6, 4 };
QuickSort(A, 0, 7);
for (auto a : A)
cout << a << " ";
cout << endl;
return 0;
}