Cod sursa(job #2270081)

Utilizator AlexandruabcdeDobleaga Alexandru Alexandruabcde Data 27 octombrie 2018 08:56:09
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <fstream>

using namespace std;

ifstream f ("algsort.in");
ofstream g ("algsort.out");

int n, H[500005];

void HeapUp (int poz)
{
    if (poz > 1)
    {
        if (H[poz] > H[poz/2])
        {
            swap(H[poz],H[poz/2]);
            HeapUp(poz/2);
        }
    }
}

void HeapDown(int poz, int n)
{
    int st, dr;
    if (2 * poz <= n)
    {
        st = H[2 * poz];
        if (2 * poz + 1 <= n)
        {
            dr = H[2 * poz + 1];
        }
        else dr = st - 1;

        if (st > dr && H[poz] < st)
        {
            swap(H[poz], H[2 * poz]);
            HeapDown(poz * 2, n);
        }
        else if (H[poz] < dr)
        {
            swap(H[poz], H[2 * poz + 1]);
            HeapDown(poz * 2 + 1, n);
        }
    }
}
int main()
{
    f >> n;

    for (int i = 1; i <= n; i++)
    {
        f >> H[i];
        HeapUp(i);
    }

    swap(H[1], H[n]);

    for (int i = n - 1; i >= 2; i--)
    {
        HeapDown(1, i);
        swap(H[1], H[i]);
    }

    for (int i = 1; i <= n; i++)
        g << H[i] << " ";
    return 0;
}