Cod sursa(job #2068719)

Utilizator bleo16783FMI Bleotiu Cristian bleo16783 Data 18 noiembrie 2017 10:41:17
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#include <iostream>
#include<fstream>
using namespace std;
#define N 500500
int h[N],i,n,x,m;
void up(int p)
{
    while(p>1&&h[p]<h[p/2])
    {
        swap(h[p],h[p/2]);
        p=p/2;
    }
}
void down(int p)
{
    while(2*p<n && ( h[p]>h[p*2] || h[p]>h[p*2+1] ) )
    {
        if(h[2*p]<h[2*p+1])
        {
            swap(h[2*p],h[p]);
            p=p*2;
        }
        else
        {
            swap(h[2*p+1],h[p]);
            p=p*2+1;
        }
    }
    if(2*p<=n && h[2*p]<h[p])
    {
        swap(h[p],h[2*p]);
    }
}
void add(int x)
{
    h[++n]=x;
    up(n);
}
int ans()
{
    int X;
    X=h[1];
    swap(h[n],h[1]);
    --n;
    down(1);
    return X;
}
int main()
{
    ifstream f("algsort.in");
    f>>m;
    for(i=0;i<m;++i)
    {
        f>>x;
        add(x);
    }
    ofstream g("algsort.out");
    for(i=0;i<m;++i)
    {
        g<<ans()<<" ";
    }
    return 0;
}