quickSort

快速排序,通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。实现代码如下。

/************************************************
*** quickSort.c 
*** 快速排序的实现
*************************************************/
#include <stdio.h>

#define CUTOFF	3

void swap( int *x, int *y )
{
	int nTmp = 0;

	nTmp = *x;
	*x = *y;
	*y = nTmp;
}

/**
*** 三数中值分割法
**/
int medin3( int A[], int nLeft, int nRight )
{
	int nCenter = 0;

	nCenter  = ( nLeft + nRight ) / 2;

	/**
	***	使 A[nLeft] <= A[nCenter] <= A[nRight]
	**/
	if ( A[nLeft] > A[nCenter] )
	{
		swap( &A[nLeft], &A[nCenter] );
	}
	if ( A[nLeft] > A[nRight] )
	{
		swap( &A[nLeft], &A[nRight] );
	}
	if ( A[nCenter] > A[nRight] )
	{
		swap( &A[nCenter], &A[nRight] );
	}

	swap( &A[nCenter], &A[nRight-1] );	/** 在位置nRight-1放置枢纽元 **/

	return	A[nRight-1];
}

void insertSort( int A[], int n )
{
	int    i = 0;
	int	   j = 0;
	int nTmp = 0;

	for (i=1; i<n; i++)
	{
		nTmp = A[i];
		for (j=i; j>0 && A[j-1]>nTmp; j--)
		{
			A[j] = A[j-1];
		}
		A[j] = nTmp;
	}
	
}

void QSort( int A[], int nLeft, int nRight )
{
	int nPovit = 0;
	int		 i = 0;
	int		 j = 0;

	if ( nLeft + CUTOFF <= nRight )	/** 设置调用快速排序的条件 **/
	{	
		nPovit = medin3( A, nLeft, nRight );	
		i      = nLeft;
		j      = nRight - 1;

		for ( ; ; )
		{
			while ( A[++i] < nPovit )	/** i跳过小于nPovit的数 **/
				;
			while ( A[--j] > nPovit )	/** j跳过大于nPovit的数 **/
				;
			if ( i < j )	/** 若i<j, 则交换对应位置的元素 **/
			{
				swap( &A[i], &A[j] );
			}
			else
			{
				break;
			}
		}
		swap( &A[i], &A[nRight-1] );	/** 存放枢纽元 **/

		QSort( A, nLeft, i - 1 );	/** 快排枢纽元左边的数 **/
		QSort( A, i + 1, nRight );	/** 快排枢纽元右边的数 **/
	}
	else
	{
		insertSort( A + nLeft, nRight - nLeft + 1 );	/** 若待排数小于4则调用插入排序 **/
	}
}

void quickSort( int A[], int n )
{
	QSort( A, 0, n - 1 );
}

int main()
{
	int i = 0;
	int n = 10;
	int nArray[10] = {8, 1, 4, 9, 0, 3, 5, 2, 7, 6};

	printf("The arrry before quickSort is: \n");
	for (i=0; i<n; i++)
	{
		printf("%d ", nArray[i]);
	}
	printf("\n\n");
	
	quickSort( nArray, n );	/** 调用快速排序 **/

	printf("The arrry after quickSort is: \n");
	for (i=0; i<n; i++)
	{
		printf("%d ", nArray[i]);
	}
	printf("\n");

	return	0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值