Heapsort [template]

Maintenance of key heaps

Clap the table! Remember to start the loop i from 1! ! !

(Here for the small root heap) Each time the top of the heap is raised, which is the current minimum value, and then the tail of the heap is placed at the beginning of the heap, and then compared with the left and right nodes, and the smaller one is exchanged until it becomes a small root heap again. .
Attach the calculation method of the father or son node:
A complete binary tree can be filled with a one-dimensional array, where a[n]the father is a[n/2]and the son is a[n*2],a[n*2+1].
 #include<iostream>
    #include<cstdio>
    using namespace std;
    int n,x;
    int hp[20000],t,a[20000];
    void push(int x) {
        t++;
        int now=t;
        hp[now]=x;
        while(now>1) {
            if(hp[now]<hp[now/2]) {
                int ls=hp[now];
                hp[now]=hp[now/2];
                hp[now/2]=ls;
                now=now/2;
            } else break;
        }
    }
    int del() {
        int res=hp[1];
        hp[1]=hp[t];
        t--;
        int now=1;
        while(2*now<=t) {
            int tp=2*now;
            if(tp<t && hp[tp]>hp[tp+1]) tp++;
            if(hp[now]>hp[tp]) {
                int ls=hp[now];
                hp[now]=hp[tp];
                hp[tp]=ls;
                now=tp;
            } else break;
        }
        return res;
    }
    int main() {
        cin>>n;
        for(int i=0; i<n; i++) {
            cin>>x;
            push(x);
        }
    //    for(int i=1; i<=n; i++) {
    //        cout<<hp[i]<<endl;
    //    }
        for(int i=0;i<n;i++){
            a[i]=del();
        }
        for(int i=0;i<n;i++){
            cout<<a[i]<<" ";
        }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325599747&siteId=291194637