排序算法 - 快速排序(C++)

// 单向扫描就地重排
int Partitation_1Way(int array[], int nIdxLeft, int nIdxRight)
{
	assert(NULL != array);
	if (nIdxLeft == nIdxRight)
		return nIdxLeft;
	
	// Take the last element as middle value.
	int nMiddleVal = array[nIdxRight];
	int nIdxSmall = nIdxLeft - 1;
	// Always true in loop:
	//     elements within [nIdxLeft, nIdxSmall] are smaller than nMidVal.
	//     elements within [nIdxSmall+1, nIdxBig] are bigger than nMidVal.
	for (int nIdxBig = nIdxLeft; nIdxBig<=nIdxRight; nIdxBig++)
		{
		if (array[nIdxBig]<=nMiddleVal)
			{
			nIdxSmall ++;
			if (nIdxSmall != nIdxBig)
				{
				int nTemp = array[nIdxSmall];
				array[nIdxSmall] = array[nIdxBig];
				array[nIdxBig] = nTemp;
				}
			}
		}
	return nIdxSmall;
}

// 双向扫描就地重排
int Partitation_2Way(int array[], int nIdxLeft, int nIdxRight)
{
	assert(NULL != array);
	if (nIdxLeft == nIdxRight)
		return nIdxLeft;
	
	// Take the first element as middle value.
	int nMidVal = array[nIdxLeft];
	int nIdxBackward = nIdxLeft;
	int nIdxForward = nIdxRight;
	for ( ; nIdxBackward < nIdxForward; )
		{
		// forward find the small one from tail, move front
		while (nIdxBackward < nIdxForward && array[nIdxForward] > nMidVal)
			nIdxForward--;
		array[nIdxBackward] = array[nIdxForward];

		// backward find the big one from head, move back.
		while (nIdxBackward < nIdxForward && array[nIdxBackward] < nMidVal)
			nIdxBackward++;
		array[nIdxForward] = array[nIdxBackward];
		}
	array[nIdxBackward] = nMidVal;
	return nIdxBackward;
	
}

void QuickSort(int array[], int nIdxLeft, int nIdxRight)
{
	if (NULL == array || nIdxLeft == nIdxRight)
		return;
	if (nIdxLeft < nIdxRight)
		{
		int nIdxMid = Partitation_1Way(array, nIdxLeft, nIdxRight);
		//int nIdxMid = Partitation_2Way(array, nIdxLeft, nIdxRight);
		QuickSort(array, nIdxLeft, nIdxMid-1);
		QuickSort(array, nIdxMid+1, nIdxRight);
		}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值