本文代码借鉴了http://blog.youkuaiyun.com/fduan/article/details/7914331
但也做了一些小的优化,就是在选择枢纽元的时候,采用了三数取中法,避免取到最大或最小的数作为枢纽元,在待排数比较多的情况下能有效减少排序的时间
#include <stdio.h>
#include <time.h>
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void disp_array( int a[], int n )
{
int i;
for( i = 0; i < n; ++i )
printf( "%d ", a[i] );
printf( "\n" );
}
int partition( int a[], int low, int high )
{
int m = low + (high - low) / 2; //采用三数取中的方法,尽量避免枢纽元素是最大数或最小数
if(a[low] >a[high])
swap(&(a[low]),&(a[high]));
if(a[m] > a[high])
swap(&(a[m]), &(a[high]));
if(a[m] > a[low])
swap(&(a[m]), &(a[low]));
int piv_val = a[low];
while( low < high )
{
while( low < high && a[high] >= piv_val )
--high;
a[low] = a[high];
while( low < high && a[low] <= piv_val )
++low;
a[high] = a[low];
}
a[low] = piv_val;
return low;
}
void qsort_recur( int a[], int low, int high )
{
int idx_piv;
if( low < high )
{
idx_piv = partition( a, low, high );
qsort_recur( a, low, idx_piv - 1 );
qsort_recur( a, idx_piv + 1, high );
}
}
void quick_sort( int a[], int n )
{
qsort_recur( a, 0, n - 1 );
}
int main()
{
clock_t start, finish;
start = clock();
int a[] = { 10,9,8,7,6,5,4,3,2,1};
int n = sizeof(a)/sizeof(int);
printf( "Before sorting: " );
disp_array( a, n );
quick_sort( a, n );
printf( "After sorting: " );
disp_array( a, n );
finish = clock();
printf("\n本次计算一共耗时: %f秒\n\n", (double)(finish-start)/CLOCKS_PER_SEC);
return 0;
}