Cod sursa(job #2203866)

Utilizator DordeDorde Matei Dorde Data 13 mai 2018 15:38:55
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.8 kb
#include <cstdio>
#include <iostream>
using namespace std;
char const in [] = "algsort.in";
char const out [] = "algsort.out";
int const NM = 5e5 + 7 , BUFF = 1e7;
int heap [NM] , n , point;
char buff [BUFF];
int getbuff ()
{
    int val = 0;
    while(! isdigit (buff [point]))
    {
        ++ point;
        if(point == BUFF)
        {
            point = 0;
            fread (buff , 1 , BUFF , stdin);
        }
    }
    while(isdigit (buff [point]))
    {
        val = val * 10 + (buff [point] - '0' );
        ++ point;
        if(point == BUFF )
        {
            point = 0;
            fread (buff , 1, BUFF , stdin);
        }
    }
    return val;
}
int father (int nod)
{
    return nod / 2;
}
int left_son (int nod)
{
    return nod * 2;
}
int right_son (int nod)
{
    return nod * 2 + 1;
}
void sift (int strat)
{
    int son = 1;
    while(son)
    {
        son = 0;
        if(left_son (strat) <= n)
        {
            son = left_son (strat);
            if(right_son (strat) <= n && heap [son] > heap [right_son (strat)])
                son = right_son (strat);
            if(heap [son] >= heap [strat])
                son = 0;
        }
        if(son)
        {
            swap (heap [son] , heap [strat]);
            strat = son;
        }
    }
}
void heapsort ()
{
    int i;
    for(i = n ; i > 0 ; -- i)
    {
        printf ("%d " , heap [1]);
        swap (heap [1] , heap [n]);
        -- n;
        sift (1);
    }
}
int main()
{
    int i;
    freopen (in , "r" , stdin);
    freopen (out , "w" , stdout);
    fread (buff , 1 , BUFF , stdin);
    n = getbuff ();
    for(i = 1 ; i <= n ; ++ i)
        heap [i] = getbuff ();
    for(i = n / 2 ; i > 0 ; -- i)
        sift (i);
    heapsort ();
    return 0;
}