#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;
}