/*堆排序*/
//根节点元素自顶向下移动到合适的位置以构成最大堆
void downToMaxHeap(vector<int> &arr, int bgn, int end)
{
int child;
int parent = bgn;
/*假根节点向下移动至合适的位置 --整个堆排序的核心代码块*/
while ((child = parent * 2 + 1) < end)
{
if ((child < end - 1) && (arr[child] < arr[child + 1]))
++child; //右孩子节点
if (arr[child] > arr[parent])
mySwap(&arr[child], &arr[parent]);
else
break;
parent = child;
}
}
//将数组构造为最大堆
void buildMaxHeap(vector<int> &arr, int bgn, int end)
{
if (bgn >= end - 1)
return;
int parent = end / 2 - 1;
while (parent >= 0)
{
downToMaxHeap(arr, parent, end);
--parent;
}
}
//堆排序
void heapSort(vector<int> &arr, int bgn, int end)
{
//构造最大堆
buildMaxHeap(arr, bgn, end);
while (end > 1)
{
mySwap(&arr[0], &arr[--end]);
downToMaxHeap(arr, 0, end);
}
}
Code-堆排序
https://blog.csdn.net/u010452388/article/details/81283998
https://www.cnblogs.com/Glory-D/p/7884525.html
原文:https://www.cnblogs.com/ljy08163268/p/11668533.html