#include <algorithm> #include <cmath> #include <time.h> #include <Windows.h> #include <iostream> using namespace std; typedef long long int _INT64; const int len = 100000; _INT64 x[len] = {0}; void getRandArrayNoRepeat() { for (int i=0; i<len; ++i) x[i] = i; random_shuffle(x, x+len); } void quickSort1(int l, int u) { if (l >= u) return; int m = l; for (int i=l+1; i<=u; i++) { if (x[i]<x[l]) { swap(x[m], x[i]); ++m; } } swap(x[l], x[m]); quickSort1(l, m-1); quickSort1(m+1, u); } void quickSort3(int l, int u) { if (l>=u) return; _INT64 t = x[l]; int i = l; int j = u+1; while (1) { do { i++; } while (i<=u && x[i]<t); do { j--; } while (x[j]>t); if (i > j) break; swap(x[i], x[j]); } swap(x[l], x[j]); quickSort3(l, j-1); quickSort3(j+1, u); } void quickSort4(int left,int right) { int i(left),j(right); _INT64 middle(0),iTemp(0); middle=x[(left+right)/2];//求中间值 middle=x[(rand()%(right-left+1))+left]; //生成大于等于left小于等于right的随机数 do{ while((x[i]<middle)&&(i<right))//从左扫描大于中值的数 i++; while((x[j]>middle) && (j>left))//从右扫描小于中值的数 j--; //找到了一对值,交换 if(i<=j) { iTemp=x[j]; x[j]=x[i]; x[i]=iTemp; i++; j--; } } while(i<=j);//如果两边扫描的下标交错,就停止(完成一次) //当左边部分有值(left<j),递归左半边 if(left<j) quickSort4(left,j); //当右边部分有值(right>i),递归右半边 if(right>i) quickSort4(i,right); } void quickSort5(_INT64 a[],int left,int right) { int i,j,temp; i=left; j=right; temp=a[left]; if(left>right) return; while(i!=j)/*找到最终位置*/ { while(a[j]>=temp && j>i) j--; if(j>i) a[i++]=a[j]; while(a[i]<=temp && j>i) i++; if(j>i) a[j--]=a[i]; } a[i]=temp; quickSort5(a,left,i-1);/*递归左边*/ quickSort5(a,i+1,right);/*递归右边*/ } int compare( const void *arg1, const void *arg2 ) { _INT64 * n1 = (_INT64*)arg1; _INT64 * n2 = (_INT64*)arg2; return *n1 - *n2; } int main() { getRandArrayNoRepeat(); cout << "test start..." << endl; //test1 DWORD test1 = GetTickCount(); quickSort3(0, len-1); test1 = GetTickCount() - test1; //test2 getRandArrayNoRepeat(); DWORD test2 = GetTickCount(); quickSort4(0, len-1); test2 = GetTickCount() - test2; //test3 getRandArrayNoRepeat(); DWORD test3 = GetTickCount(); quickSort5(x, 0, len-1); test3 = GetTickCount() - test3; //test4 getRandArrayNoRepeat(); DWORD test4 = GetTickCount(); qsort(x, len, sizeof(_INT64), compare); test4 = GetTickCount() - test4; cout << "test1's running time = " << test1 << " ms." <<'/n' << "test2's running time = " << test2 << " ms." <<'/n' << "test3's running time = " << test3 << " ms." <<'/n' << "test4's running time = " << test4 << " ms." <<'/n'; return 0; } 测试结果: //10个元素数组 test start... test1's running time = 32 ms. test2's running time = 32 ms. test3's running time = 31 ms. test4's running time = 94 ms. test start... test1's running time = 406 ms. test2's running time = 313 ms. test3's running time = 328 ms. test4's running time = 1109 ms. 请按任意键继续. . . //1000万个 test start... test1's running time = 4859 ms. test2's running time = 3656 ms. test3's running time = 3922 ms. test4's running time = 13063 ms.