H面试程序(14): 快速排序法

本文代码借鉴了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;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值