这里基于循环实现,还可以基于递归实现,递归实现可参考《算法导论》
#include <iostream>
using namespace std;
void percolate_down(int *a, int hole, int size){
int tmp = a[hole];
int child;
while (hole * 2 + 1 < size){
child = hole * 2 + 1;
if (child + 1 < size && a[child + 1] > a[child])
child++;
if (tmp < a[child])
a[hole] = a[child];
else
break;
hole = child;
}
a[hole] = tmp;
}
void heap_sort(int *a, int size){
//建堆
for (int i = size / 2 - 1; i >= 0; --i){
percolate_down(a, i, size);
}
//将最大值逐个移到数组末尾
for (int i = size - 1; i > 0; --i){
swap(a[0], a[i]);
percolate_down(a, 0, i);
}
}
int main(){
int a[] = {2, 3, 4, 1, 0, 7, 8, 9, 6, 5};
heap_sort(a, 10);
int ttt = 0;
return 0;
}