#include<iostream>
#include<cstdio>
#include<cstring>
//
using namespace std;
int partition(int data[], int begin, int end)
{
int key = data[begin];
while(begin < end) {
while(data[end]>=key && begin<end)
end--;
data[begin] = data[end];
while(data[begin]<=key && begin<end)
begin++;
data[end] = data[begin];
}
data[begin] = key;
return begin;
}
void quickSort(int data[], int begin, int end)
{
if(begin >= end)
return;
int mid = partition(data, begin, end);
quickSort(data, begin, mid-1);
quickSort(data, mid+1, end);
}
int main()
{
int data[] = {2,4,1,3,0,6,7,2};
quickSort(data, 0, 7);
for(int i=0; i<8; ++i)
cout<<data[i]<<" ";
//system("pause");
return 0;
}
根据编程珠玑的解释,有一个能预防所有元素相等情况下quicksort退化到n平方的算法,虽然比较次数增多,但是平均比较次数和平均复杂度均有提升:
void quickSort(int data[], int l, int u)
{
int k = random(l,u);
swap(data, k, l);
if(l>=u)
return;
int p = data[l], i=l, j=u+1;
while(true)
{
do {
i++;
} while(i<=u && data[i]<p);
do{
--j;
} while(data[j] > p);
if(i>j)
break;
int tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
int tmp = data[l];
data[l] = data[j];
data[j] = tmp;
quickSort(data, l, j-1);
quickSort(data, j+1, u);
}