堆排序

#include<bits/stdc++.h>
using namespace std;

const int maxn = 100000+5;
int heap[maxn],_size;
void put(int k){
    heap[++_size]=k;
    int now=_size;
    while(now>1){
        int nxt = now >> 1;
        if(heap[now]>heap[nxt])return;
        swap(heap[now],heap[nxt]);
        now = nxt;
    }
    
}
void get(){
    int res = heap[1];
    heap[1] = heap[_size--];
    heap[_size+1] = res;
    int now = 1;
    while(now*2<=_size){
        int nxt = now << 1;
        if(nxt<_size&&heap[nxt]>heap[nxt+1])nxt++;
        if(heap[now]<=heap[nxt])return;
        swap(heap[now],heap[nxt]);
        now = nxt;
    }
}
int main(){
    int n,tot=0;
    cin>>n;
    for(int i=1;i<=n;i++){
        int b;
        cin>>b;
        put(b);
    }
    for(int i=1;i<n;i++)get();
    for(int i=1;i<=n;i++) cout<<heap[i]<<" ";
}

 

posted @ 2018-01-30 18:16  Ed_Sheeran  阅读(98)  评论(0)    收藏  举报