Definition
一种树形选择排序,即:在排序过程中,将整个序列看成一颗完全二叉树的顺序存储结构。
两个步骤:
- 构造初始堆,满足:每个分支结点对应的值总是大于(小于)后继结点对应的值,这样的堆称为大顶堆(小顶堆)
- 将堆顶(即根结点)出堆,得到最大值(最小值),将序列的最后一个元素放到堆顶,调整堆,使得依然满足大顶堆(小顶堆)
重复上述过程,直到堆内剩下一个元素,这时我们便得到了整个排序序列
Implementation
这里,我们的数据存储的下标从 1 1 1 开始, A [ 0 ] A[0] A[0] 用来作为一个临时的存储位置:
void sort(ElementType* seq, int n){
// initialize heap
initialize(seq, n);
// 'cause the first node is the largest
for(int k = n; k > 1;k--){
swap(seq, 1, k);
adjust(seq, 1, k);
}
}
void initialize(ElementType* seq, int n){
// build max heap by starting adjusting from the last branch node to root node
for(int i = n / 2;i >= 0; i--){
adjust(seq, i, n);
}
void adjust(ElementTYpe* seq, int k, int n){
// temporarily store value we are going to adjust down
seq[0] = seq[k];
// i is the left child's index and k is the parent's index
for(int i = 2 * k; i <= n; i *= 2){
// select child with larger value
if(i < n && seq[i] < seq[i + 1]){
i = i + 1;
}
// if larger than this child, break 'cause children are already in order
if(seq[0] > seq[i + 1){
break;
}
// else, move up child's value and let its index be the parent's index in next loop
else{
seq[k] = seq[i];
k = i;
}
}
// place the value in the final position
seq[k] = seq[0];
}
最终,输出的是一个从小到大的序列。根据不同要求,选择构造小顶堆或者是大顶堆