输入n个正整数,使用堆排序算法将它们按从小到大的顺序进行排序。
解题思路:
我们先利用自上向下调整构造出大顶堆,然后我们可以知道根节点是最大的,我们将根节点与最后一个结点进行互换,实现一次排序,获得了最大的值,稳定在最后一个位置,然后调整根节点,重复上述工作,最终实现整个堆,自上向下为从小到大排序。
完整代码如下:
#include <iostream>
using namespace std;
const int maxn = 1001;
int heap[maxn];
void downAdjust(int low,int high){
int i = low, j = i*2;//i为要调整的结点,j为其左儿子。
while(j<=high){//存在结点孩子
if(j+1<=high&&heap[j+1]>heap[j]){
//存在右儿子,且右儿子的权值大于左儿子。
j = j+1;
}
if(heap[j]>heap[i]){
swap(heap[j],heap[i]);
i = j;//继续调整原始结点。
j = i*2;
}
else{
break;//孩子已经比要调整的小了。
}
}
}
void createHeap(int n){
for(int i=n/2;i>=1;i--){//因为叶子结点没有儿子,要从最后一个非叶子结点的开始,即为n/2;
//因为我们规定了堆,必定是一个完全二叉树。
downAdjust(i,n);
}
}
void heapsort(int n){
for(int i=1;i<=n;i++){
swap(heap[1],heap[n+1-i]);//每次交换堆顶元素
downAdjust(1,n-i);//一趟后把重新调整剩余最大值到堆顶。
}
}
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>heap[i];
}
createHeap(n);
heapsort(n);
for(int i=1;i<=n;i++){
if(i!=1){
cout<<" ";
}
cout<<heap[i];
}
cout<<endl;
return 0;
}