算法描述:每次选择一个值,将比它小的值放在它的左边,比它大的值放在它的右边。不断递归调用即可。
时间复杂度:平均复杂度O(nlgn),最大复杂度为O(n2),最小复杂度为O(n)。有序程度越高,复杂度越大。最高时是每次换位都是全部分到同一边。但快速排序的稳定性比较强, 大部分都是接近于平均情况。如果每次取得值选择的是随机值,那么就稳定在平均复杂度了。
代码如下(随机化版本)
#include <bits/stdc++.h>
using namespace std;
int a[10000];
int random(int start,int end)
{
int t;
srand(time(NULL));
while(true)
{
t=rand()%(end+1);
if(t>=start)
{
return t;
}
}
}
void QuickSort(int a[], int low, int high)
{
if(low > high)
{
return ;
}
int h = random(low, high);
swap(a[h], a[low]);
int first = low;
int last = high;
int key = a[low];
while(first < last)
{
while(first < last && a[last] >= key)
{
--last;
}
a[first] = a[last];