Cod sursa(job #1255323)

Utilizator mihail.jianuJianu Mihail mihail.jianu Data 4 noiembrie 2014 18:07:37
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.99 kb
/// heap sort cu heap iterativ, de mana
#include<cstdio>
const int N=500000;
const int INF=(1<<31)-1;
int min(int a,int b){
    if(a<b)
        return a;
    return b;
}
class MinHeap{
    public:
        int v[2*N+2];
        int l;
        bool empty(){
            return l==0;
        }
        int top(){
            return v[1];
        }
        void push(int x){
            v[++l]=x;
            int p=l;
            while(p>1&&v[p]<v[p/2]){
                change(p,p/2);
                p/=2;
            }
        }
        void pop(){
            bool f=true;
            v[1]=v[l--];
            v[l+1]=INF;
            int p=1;
            while(f){
                f=false;
                if(p*2+1<=l){
                    if(min(v[p*2],v[p*2+1])<v[p])
                        if(v[p*2]<v[p*2+1]){
                            change(p,p*2);
                            p=p*2;
                            f=true;
                        }
                        else{
                            change(p,p*2+1);
                            p=p*2+1;
                            f=true;
                        }
                }
                else
                    if(p*2<=l)
                        if(v[p*2]<v[p]){
                            change(p,p*2);
                            p=p*2;
                            f=true;
                        }
            }
        }
    private:
        void change(int p1,int p2){
            int aux=v[p1];
            v[p1]=v[p2];
            v[p2]=aux;
        }
};
MinHeap h;
int n;
int main(){
    freopen("algsort.in","r",stdin);
    freopen("algsort.out","w",stdout);
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        int nr;
        scanf("%d",&nr);
        h.push(nr);
    }
    int op=0;
    while(!h.empty()){;
        op++;
        if(op==100001){
           op++;
           op--;
        }
        printf("%d ",h.top());
        h.pop();
    }
    return 0;
}