Cod sursa(job #1545735)

Utilizator Ionut228Ionut Calofir Ionut228 Data 6 decembrie 2015 23:37:49
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
#include <algorithm>

using namespace std;

ifstream fin("algsort.in");
ofstream fout("algsort.out");

int N, M;
int V[500005], H[500005];

int left_son(int x)
{
    return 2 * x;
}

int right_son(int x)
{
    return 2 * x + 1;
}

int father(int x)
{
    return x / 2;
}

void percolate(int nod) // urca
{
    while ((nod > 1) && H[nod] < H[father(nod)])
    {
        swap(H[nod], H[father(nod)]);
        nod = father(nod);
    }
}

void sift(int nod) // coboara
{
    int son = 1;
    while (son)
    {
        son = 0;
        if (left_son(nod) <= M)
        {
            son = left_son(nod);
            if (right_son(nod) <= M && H[right_son(nod)] < H[left_son(nod)])
                son = right_son(nod);
            if (H[son] >= H[nod])
                son = 0;
        }

        if (son)
        {
            swap(H[nod], H[son]);

            nod = son;
        }
    }
}

void cut(int nod)
{
    if (nod == 0)
        return;

    swap(H[nod], H[M]);
    --M;

    if ((nod > 1) && H[nod] < H[father(nod)])
        percolate(nod);
    else
        sift(nod);
}

int main()
{
    fin >> N;
    for (int i = 1, x; i <= N; ++i)
    {
        fin >> x;
        H[++M] = x;

        percolate(M);
    }

    while (M)
    {
        V[N - M + 1] = H[1];
        cut(1);
    }

    for (int i = 1; i <= N; ++i)
        fout << V[i] << ' ';

    fin.close();
    fout.close();
    return 0;

}