【算法分析】
● 堆排序依托于完全二叉树的结构,需要解决如下两个问题:
建初堆:如何将一个无序序列建成一个堆?
调整堆:去掉堆顶元素,在堆顶元素改变之后,如何调整剩余元素成为一个新的堆?
● “筛选法”对无序序列构建大根堆的算法步骤:
构建包含n个数的无序序列对应的完全二叉树;
依序遍历第i = ⌊n/2⌋ ~ 1个结点,若第2i、2i+1个结点中的较大值,比第i个结点的值大,交换。
● 堆排序算法步骤:
首先,对无序序列建初堆;
其次,在初始堆的基础上,反复交换堆顶元素和最后一个元素,然后重新调整堆,直至最后得到一个有序序列。
【算法代码】
#include<bits/stdc++.h>
using namespace std;
const int maxn=1005;
int h[maxn]; //save heap
int n;
void swap(int a,int b) {
int t=h[a];
h[a]=h[b];
h[b]=t;
}
void siftdown(int i) {
int t,flag=0;
while(i<=n/2 && flag==0) {
if(h[i]<h[i*2]) t=i*2;
else t=i;
if(i*2+1<=n) { //if has right child
if(h[t]<h[i*2+1]) t=i*2+1;
}
if(t!=i) {
swap(t,i);
i=t;
} else flag=1;
}
}
void creat() {//create heap
for(int i=n/2; i>=1; i--) siftdown(i);
}
void heapsort() {
while(n>1) {
swap(1,n);
n--;
siftdown(1);
}
}
int main() {
int tot;
cin>>tot;
for(int i=1; i<=tot; i++) cin>>h[i];
n=tot;
creat();
heapsort();
for(int i=1; i<=tot; i++) cout<<h[i]<<" ";
return 0;
}
/*
in:
12
66 6 36 7 22 17 12 2 19 25 28 1
out:
1 2 6 7 12 17 19 22 25 28 36 66
*/
【参考文献】
https://blog.51cto.com/ahalei
https://blog.51cto.com/ahalei/1425314
https://blog.51cto.com/ahalei/1427156
https://blog.csdn.net/hnjzsyjyj/article/details/127840651