参考文章:堆排序原理及算法实现(最大堆)
堆排序代码
#include <iostream>
using namespace std;
void BigHeapAdjust(int32_t numList[], int32_t len, int32_t index){
auto i = index;
auto j = i * 2 + 1; //得到i的左孩子
auto tmp = numList[i];
while(j <= len) {
if (j < len && numList[j] < numList[j+1]) {
//右孩子比左孩子大,就直接取大的数比较
j++;
}
//与index节点比较
if (tmp < numList[j]) {
numList[i] = numList[j];
//继续监测子节点
i = j;
j = i * 2 + 1;
}
else {
break;
}
}
numList[i] = tmp;
}
void HeapSort(int32_t numList[], int32_t len) {
auto index = len / 2 - 1; //最后一个非叶子节点
for (; index >= 0; index--) {
BigHeapAdjust(numList, len, index);
}
for (index = len - 1; index > 0; index--) {
auto tmp = numList[index];
numList[index] = numList[0];
numList[0] = tmp;
BigHeapAdjust(numList, index - 1, 0); //从根节点开始判断
}
}
void main() {
int32_t numList[] = { 31, 41, 59, 26, 41, 58, 12 };
int32_t count = sizeof(numList) / sizeof(numList[0]);
HeapSort(numList, count);
for (auto num : numList) {
std::cout << num << " ";
}
std::cout << std::endl;
}
返回排序算法分析总结