Cod sursa(job #1232557)

Utilizator ZenusTudor Costin Razvan Zenus Data 23 septembrie 2014 10:07:50
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.83 kb
#include <cstdio>
#include <algorithm>

using namespace std;

#define NMAX 500001

int H[2*NMAX],P[NMAX];
int i,N,current;

void Up(int P)
{
    while (P>1)
    {
        if (H[P]>H[P/2])
        {
            swap(H[P],H[P/2]);
            P=P/2;
        } else return ;
    }
}

void Down(int P)
{
    if (2*P>N) return ;

    if (H[2*P]>((2*P+1>N) ? -1 : H[2*P+1]))
    {
        swap(H[P],H[2*P]);
        Down(2*P);
    }
    else
    {
        swap(H[P],H[2*P+1]);
        Down(2*P+1);
    }
}

int main()
{
freopen("algsort.in","r",stdin);
freopen("algsort.out","w",stdout);

scanf("%d",&N);

for (i=1;i<=N;++i)
{
    scanf("%d",&H[i]);
    Up(i);
}

while (N)
{
    P[++P[0]]=H[1];
    swap(H[1],H[N]);
    --N,Down(1);
}

for (i=P[0];i;--i)
printf("%d ",P[i]);

return 0;
}