一步一步优化的快速排序,速度比插入排序快很多,而且可以很方便的引入随机算法来避免最差情况。
#include<iostream> #include<string.h> #include<stdio.h> #include<algorithm> #include <sys/times.h> //#include <time.h> using namespace std; #define DEBUG const int MAX = 1000000; int cutoff = 10; void swap( int *data, int i, int j) { int temp = data[i]; data[i] = data[j]; data[j] = temp; } void InsertSort3( int *data, int n) { int i, j, temp; for( i = 1; i< n; i++) { temp = data[i]; for( j = i; data[j - 1] > temp && j > 0; j--) data[j ] = data[j - 1]; data[j] = temp; } } void QuickSort1( int *data, int l, int u) { if( l >= u) return ; int m = l; for( int i = l + 1; i <=u; i++) { if( data[i] < data[l] ) swap(data, ++m, i); } swap(data, l, m); QuickSort1(data, l, m - 1); QuickSort1(data, m + 1, u); } void QuickSort2( int *data, int l ,int u) { int i, j; if ( l >= u) return; int temp; temp = data[l]; i = l; j = u + 1; while( true) { do i++; while( i <= u && data[i] < temp); do j--; while( data[j] > temp); if( i > j ) break; swap( data, i, j); } swap( data, l, j); QuickSort2(data, l , j -1); QuickSort2(data, j + 1 , u); } void QuickSort3( int *data, int l ,int u) { int i, j; if ( u - l < cutoff) return; swap(data,l, rand() %( u - l ) + l); int temp; temp = data[l]; i = l; j = u + 1; while( true) { do i++; while( i <= u && data[i] < temp); do j--; while( data[j] > temp); if( i > j ) break; int t = data[i]; data[i] = data[j]; data[j] = t; } swap( data, l, j); QuickSort3(data, l , j -1); QuickSort3(data, j + 1 , u); } int main() { srand(5); int sec_per_dida = sysconf( _SC_CLK_TCK); int data[ MAX]; int data2[MAX]; const int denominator = MAX * 10; double BegTime, EndTime; for( int i = 0; i < MAX; i++) { data[i] = rand() % denominator; } memcpy(data2, data, sizeof(int) * MAX); BegTime = clock(); QuickSort1( data, 0, MAX - 1); EndTime = clock(); printf("time of QucikSort1 test is : %g ms \n", (EndTime - BegTime ) / sec_per_dida); memcpy(data, data2, sizeof(int)*MAX); BegTime = clock(); QuickSort2( data, 0, MAX - 1); EndTime = clock(); printf("time of QucikSort2 test is : %g ms \n", (EndTime - BegTime ) / sec_per_dida); memcpy(data, data2, sizeof(int)*MAX); BegTime = clock(); QuickSort3( data, 0, MAX - 1); InsertSort3( data, MAX); EndTime = clock(); printf("cutoff:%d\ttime of QucikSort3 && InsertSort test is : %g ms \n",cutoff, (EndTime - BegTime ) / sec_per_dida); #ifdef DEBUG while( cutoff < 100 ) { cutoff += 10; memcpy(data, data2, sizeof(int)*MAX); BegTime = clock(); QuickSort3( data, 0, MAX - 1); InsertSort3( data, MAX); EndTime = clock(); printf("cutoff: %d", cutoff); printf("\ttime of QucikSort3 && InsertSort test is : %g ms \n", (EndTime - BegTime ) / sec_per_dida); } #endif return 0; }测试结果: