0
点赞
收藏
分享

微信扫一扫

堆排序模板(最小堆)

阎小妍 2022-03-12 阅读 56
#include <iostream>
using namespace std;
int h[10000];
int n;
void siftdown(int i);
int deletemin();
int main (){
    cin>>n;
    int i;
    for(i=1;i<=n;i++){
        cin>>h[i];
    }
    for(i=n/2;i>=1;i--){
        siftdown(i);
    }
    int num=n;
    for(i=1;i<=num;i++){
        if(i>1)cout<<" ";
        cout<<deletemin();
    }
    return 0;
}
int deletemin(){
    int t;
    t=h[1];
    h[1]=h[n];
    n--;
    siftdown(1);  //取出最小值并将最后一个元素放入h[1]后要调整位置使重新符合最小堆性质。
    return t;
}
void siftdown(int i){
    int flag=0;
    int t;
    while(flag==0&&i*2<=n){
        t=i;
        if(h[i*2]<h[i]){
            t=i*2;
        }
        if(i*2+1<=n&&h[i*2+1]<h[t]){
            t=i*2+1;
        }
        if(i==t)flag=1;
        else {
            swap(h[t],h[i]);
            i=t;
        }
    }
    return ;
}
/*
5
1 9 3 5 2    //输入
1 2 3 5 9    //输出
*/
举报

相关推荐

0 条评论