Cod sursa(job #1465402)

Utilizator crysstyanIacob Paul Cristian crysstyan Data 27 iulie 2015 12:06:52
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
#include <fstream>
#include <algorithm>
#define NMAX 1000005

using namespace std;

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

int heap[NMAX], i, n, m = 0, nr;

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

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

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

void go_up(int k)
{
    while (heap[k] < heap[father(k)])
    {
        swap(heap[k], heap[father(k)]);
        k = father(k);
    }
}

void go_down(int k)
{
    int aux = 0;

    do
    {
        aux = 0;

        if (left_son(k) <= m)
            aux = left_son(k);

        if (right_son(k) <= m && heap[right_son(k)] < heap[aux])
            aux = right_son(k);

        if (heap[left_son(k)] > heap[k] && heap[right_son(k)] > heap[k])
            aux = 0;

        if (aux != 0)
        {
            swap(heap[aux], heap[k]);
            k = aux;
        }
    }while (aux);
}

void insert_heap(int x)
{
    heap[++m] = x;
    go_up(m);
    go_down(1);
}

void delete_heap(int k)
{
    heap[k] = heap[m];
    m --;
    go_down(k);
}

int main()
{
    f >> n;

    for (i=1; i<=n; ++i)
    {
        f >> nr;
        insert_heap(nr);
    }

    while (m)
    {
        g << heap[1] << " ";
        delete_heap(1);
    }
    return 0;
}