Cod sursa(job #2288012)

Utilizator LucianTLucian Trepteanu LucianT Data 22 noiembrie 2018 19:18:59
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <fstream>
using namespace std;

const int maxN=5e5+1;

int n,sz;
int heap[maxN];

void heapUp(int nod){
    while(nod>1 && heap[nod]>heap[nod/2]){
        swap(heap[nod],heap[nod/2]);
        nod/=2;
    }
}

void heapDown(int nod){
    int change=0;
    while(nod!=change){
        change=nod;

        if(2*change<=sz && heap[nod]<heap[2*change])
            nod=2*change;

        if(2*change+1<=sz && heap[nod]<heap[2*change+1])
            nod=2*change+1;

        swap(heap[nod],heap[change]);
    }
}

int main(){
    ifstream cin("algsort.in");
    ofstream cout("algsort.out");

    cin>>n;
    for(int i=1;i<=n;i++){
        int x;
        cin>>x;
        heap[++sz]=x;
        heapUp(sz);
    }

    while(sz>0){
        swap(heap[1],heap[sz]);
        sz--;
        heapDown(1);
    }

    for(int i=1;i<=n;i++)
        cout<<heap[i]<<" ";

    return 0;
}