堆排序

#include <iostream>
using namespace std;

//取左孩子节点坐标
#define GetLeftChild(x) (2*(x)+1)
//取右孩子节点坐标 这里可能不需要
#define GetRightChild(x) (2*(x)+2)

void Show(int* pList, int nCount)
{
	for (int nIndex = 0; nIndex < nCount; nIndex++)
		cout << pList[nIndex] << "\t";
	cout << endl;
}

/*
进行自顶到底的调整
*/
void BuildDown(int* pList,int nCount,int nRootIndex)
{
	//获取根节点的数据
	int nRootData = pList[nRootIndex];

	//取得左节点的坐标
	int nLeftIndex = GetLeftChild(nRootIndex);

	while (nLeftIndex < nCount)
	{
		//如果有右孩子节点而且有孩子节点大于左孩子节点
		if (nLeftIndex != nCount - 1 && pList[nLeftIndex + 1] > pList[nLeftIndex])
			nLeftIndex++;//指向右孩子节点

		//如果最大的孩子节点还比根节点数据大的话
		if (nRootData < pList[nLeftIndex])
		{
			//最大孩子节点向上移动
			pList[nRootIndex] = pList[nLeftIndex];

			//设置新的根节点坐标
			nRootIndex = nLeftIndex;

			//设置新的左孩子节点坐标
			nLeftIndex = GetLeftChild(nRootIndex);
		}
		else
			break;
	}

	//设置节点的数据
	pList[nRootIndex] = nRootData;
}

/*
堆排序
*/
void HeapSort(int* pList,int nCount)
{
	//构建堆
	for (int nRootIndex = (nCount - 2) / 2; nRootIndex >= 0; nRootIndex--)
		BuildDown(pList, nCount, nRootIndex);

	//调整为有序序列
	for (int nIndex = nCount - 1; nIndex >= 0; nIndex--)
	{
		int nSave = pList[0];
		pList[0] = pList[nIndex];
		pList[nIndex] = nSave;
		BuildDown(pList, nIndex, 0);
	}
}


int main(int argc, char* argv[], char* enp[])
{
	int pList[] = {15,78,95,65,35,12,47,55,22,77};
	int nCount = sizeof(pList) / sizeof(int);
	HeapSort(pList, nCount);
	Show(pList, nCount);
	system("pause");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值