Cod sursa(job #2068710)

Utilizator stefantagaTaga Stefan stefantaga Data 18 noiembrie 2017 10:38:06
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.99 kb
#include <fstream>

using namespace std;
ifstream f("algsort.in");
ofstream g("algsort.out");
int n,h[500001],q;
void up(int p)
{
    if (p>1&&h[p]>h[p/2])
    {
        swap(h[p],h[p/2]);
        up(p/2);
    }
}
void add(int x)
{
    h[++q]=x;
    up(q);
}
void down(int p)
{
    if (p*2+1<=q&&(h[p*2]>h[p]||h[p*2+1]>h[p]))
    {
        if (h[p*2]>h[p*2+1])
        {
            swap(h[p],h[p*2]);
            down(p*2);
        }
        else
        {
            swap(h[p],h[p*2+1]);
            down(p*2+1);
        }
    }
    else
    if (p*2<=q&&h[p*2]>h[p])
    {
        swap(h[p*2],h[p]);
    }
}
void del(int p)
{
    swap(h[p],h[q]);
    q--;
    up(p);
    down(p);
}
int v[500001];
int main()
{
    int i,x,t=0;
    f>>n;q=0;
    for (i=1;i<=n;i++)
    {
        f>>x;
        add(x);
    }t=0;
    while (q)
    {
        v[++t]=h[1];
        del(1);
    }
    for (i=t;i>=1;i--)
    {
        g<<v[i]<<" ";
    }
    return 0;
}