Cod sursa(job #2078552)

Utilizator trutruvasilicaHuhurez Marius trutruvasilica Data 29 noiembrie 2017 18:44:47
Problema Sortare prin comparare Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include <fstream>

using namespace std;
ifstream fin("algsort.in");
ofstream fout("algsort.out");
int v[550000],n;
int left_son(int x)
{
    return x*2;
}
int right_son(int x)
{
    return x*2+1;
}
int father(int x)
{
    return x/2;
}
void down_heap(int x)
{
    int son=-1;
    while(son)
    {
        if(left_son(x)<=n) son=left_son(x);
        if(right_son(x)<=n && v[right_son(x)] < v[son]) son=right_son(x);
        if(v[x]<= v[son] ) son=0;
        if(son)
        {
            swap(v[x],v[son]);
            x=son;
        }
    }
}
void up_heap(int x)
{
    int val=v[x];
    while(x>1 && val < v[father(x)])
    {
        v[x]=v[father(x)];
        x=father(x);
    }
    v[x]=val;
}
void build()
{
    for(int i=n/2;i>=1;i--)
    {
        down_heap(i);
    }
}
void delete_node(int x)
{
    v[x]=v[n];
    if(x>1 && v[x] < v[father(x)]) up_heap(x);
    else down_heap(x);
}
int main()
{
    int i;
    fin>>n;
    for(i=1;i<=n;i++) fin>>v[i];
    build();
    while(n)
    {
        fout<<v[1]<<" ";
        delete_node(1);
        n--;
    }
}