Cod sursa(job #2083052)

Utilizator CozehNita Horia Teodor Cozeh Data 7 decembrie 2017 00:23:49
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.09 kb
#include <fstream>
using namespace std;

ifstream fin("algsort.in");
ofstream fout("algsort.out");

int n,heap[500010],m;

void add(int val){
    heap[++n] = val;
    int pos = n;
    while(pos != 1 && heap[pos] < heap[pos/2]){
        swap(heap[pos],heap[pos/2]);
        pos /= 2;
    }
}

void deletepos(int pos){
    swap(heap[pos],heap[n]);
    --n;
    while(pos<=n){
        int best = 0,mx = heap[pos];
        if(2*pos <= n && mx > heap[2*pos]){
            mx = heap[2*pos];
            best = 1;
        }
        if(2*pos+1 <= n && mx > heap[2*pos+1]){
            mx = heap[2*pos+1];
            best = 2;
        }
        if(best == 0) break;
        else if(best == 1){
            swap(heap[pos],heap[2*pos]);
            pos *= 2;
        }
        else{
            swap(heap[pos],heap[2*pos+1]);
            pos = pos*2+1;
        }
    }
}

int main()
{
    int i,nr;
    fin>>m;
    for(i = 0 ; i < m; i++){
        fin>>nr;
        add(nr);
    }
    for(i = 1 ; i <= m; i++){
        fout<<heap[1]<<" ";
        deletepos(1);
    }
}