每日一题(94) - 堆排序

题目:基于数组的堆排序

思路:主要分为两步

(1)对无序数组调整成大根堆(从小到大的排序)

<1> 对非叶子结点进行调整 

<2> 从最后一个非叶子结点开始,一直到根结束

<3> 每次调整,都调整一条路径,从待调整元素的位置开始,一直到叶子结点为止。

(2)把堆顶与待排序的最后一个元素交换,之后调整堆

代码:

void Swap(int& nFirst,int& nSec)
{
	int nTmp = nFirst;
	nFirst = nSec;
	nSec = nTmp;
}

/*调整堆:由上往下调整,每次调整都处理一条路径*/
void HeapAdjust(int nArr[],int nLen,int nHole)
{
	int nKey = nArr[nHole];
	for (int nChild = 2 * nHole;nChild <= nLen;nChild *= 2)
	{
		//找最大的孩子
		if (nChild < nLen && nArr[nChild + 1] > nArr[nChild])
		{
			nChild++;
		}
		//最大孩子与父亲比较
		if (nArr[nChild] < nKey)
		{
			break;
		}
		nArr[nHole] = nArr[nChild];
		nHole = nChild;//下一次调整nHole		
	}
	nArr[nHole] = nKey;
}

/*对待排序元素,先调整成大根堆,后排序*/
void HeapSort(int nArr[],int nLen)
{
	//调整
	for (int i = nLen / 2;i >= 1;i--)
	{
		HeapAdjust(nArr,nLen,i);
	}
	//排序
	for (int i = nLen;i > 1;i--)
	{
		Swap(nArr[i],nArr[1]);
		HeapAdjust(nArr,i - 1,1);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值