Cod sursa(job #1465956)

Utilizator crysstyanIacob Paul Cristian crysstyan Data 28 iulie 2015 12:49:35
Problema Sortare prin comparare Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.65 kb
#include <fstream>
#include <algorithm>
#define NMAX 500001
#define MAX 2000000000

using namespace std;

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

int heap[NMAX], n = 0, nr, x, i, puteri2[] = {1, 2, 4, 8, 16, 32, 64, 128};

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 get_down(int k)
{
    int aux;

    do
    {
        aux = 0;

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

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

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

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

void get_up(int k)
{
    while (k > 1 && heap[k] < heap[father(k)])
    {
        swap(heap[k], heap[father(k)]);
        k = father(k);
    }
}

void insert_heap(int x)
{
    heap[++n] = x;
    get_up(n);
}

void delete_heap(int k)
{
    heap[k] = heap[n];
    heap[n] = MAX;
    n --;
    get_down(k);
}

void afisare()
{
    int i = 0;

    while (puteri2[i] <= n)
    {
        for (int j = puteri2[i]; j <= puteri2[i+1] - 1 && j <= n; ++j)
            g << heap[j] << " ";
      g << '\n';
      i ++;
    }
    g << '\n';
}

int main()
{
    f >> nr;

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

      //  afisare();

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