#include <iostream>
using std::cin;
using std::cout;
unsigned int GetLchild(unsigned int iPos)
{//注:堆排序中的树是完全2叉树,如果父亲节点是iPos那么左孩子是2 * iPos
return 2 * iPos;
}
unsigned int GetRchild(unsigned int iPos)
{//注:堆排序中的树是完全2叉树,如果父亲节点是iPos那么右孩子是2 * iPos + 1
return 2 * iPos + 1;
}
void Swap(int &a, int &b)
{//值交换
int temp = a;
a = b;
b = temp;
}
void MaxHeapify(int * iArry, unsigned int iPos)
{//父亲节点和儿子节点比较和交换
int iLchild = GetLchild(iPos);
int iRchild = GetRchild(iPos);
int iLargest = iPos;
if (iLchild <= iArry[0] && iArry[iLchild] > iArry[iPos]) iLargest = iLchild;
if (iRchild <= iArry[0] && iArry[iRchild] > iArry[iLargest]) iLargest = iRchild;
if (iLargest != iPos){
Swap(iArry[iLargest], iArry[iPos]);
MaxHeapify(iArry, iLargest);//递归把原iPos的值放到合适的位置
}
}
void BuildMaxHeap(int * iArry)
{//自底向上建立大顶堆
//由于是完全2叉树,所以节点 n / 2 + 1到 n 的节点都是叶子节点
//我们建堆得时候只需要从最后的节点n / 2开始到根节点调整即可
for (unsigned int iPos = iArry[0] / 2; iPos != 0; --iPos){
MaxHeapify(iArry, iPos);
}
}
void HeapSort(int * iArry)
{//进行堆排序,每次把最后一个未排序的跟根节点(最大的)交换
//实现从小到大排序
BuildMaxHeap(iArry); //建立大顶堆
for (unsigned int iPos = iArry[0]; iPos >= 1; --iPos){
Swap(iArry[1], iArry[iPos]);
iArry[0]--;
MaxHeapify(iArry, 1);
}
}
int main(void)
{
unsigned int iLen;
while (cin >> iLen){
int * iArry = new int [iLen + 1];
if (iLen == 0) return 0;
iArry[0] = iLen;
for (unsigned int i = 1; i <= iLen; ++i) cin >> iArry[i];
HeapSort(iArry);
for (unsigned int i = 1; i <= iLen; ++i) cout << iArry[i] << ' ';
cout << '\n';
delete []iArry;
}
return 0;
}
堆排序
最新推荐文章于 2025-03-24 22:59:14 发布