Cod sursa(job #1053978)

Utilizator saregardAndrei Tarba saregard Data 13 decembrie 2013 07:25:54
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include <fstream>
using namespace std;
ifstream f("algsort.in");
ofstream g("algsort.out");
int n=0, heap[500001];

void urca(int poz)
{
    while(poz>1 && heap[poz]<heap[poz/2])
    {
        swap(heap[poz], heap[poz/2]);
        poz/=2;
    }
}
void coboara(int poz)
{
    int poz2;
    while(poz*2+1<=n && (heap[poz]>heap[poz*2] || heap[poz]>heap[poz*2+1]))
    {
        poz2=poz*2;
        if(heap[poz2+1]<heap[poz2])
            poz2++;
        swap(heap[poz], heap[poz2]);
        poz=poz2;
    }
    if(poz*2==n && heap[poz]>heap[poz*2])
        swap(heap[poz], heap[poz*2]);
}
void inserare(int x)
{
    n++;
    heap[n]=x;
    urca(n);
}
void stergere_min()
{
    g<<heap[1]<<' ';
    heap[1]=heap[n--];
    coboara(1);
}

int main()
{
    int N, i, x;
    f>>N;
    for(i=1; i<=N; i++)
    {
        f>>x;
        inserare(x);
    }
    for(i=1; i<=N; i++)
        stergere_min();
    return 0;
}