Cod sursa(job #758006)

Utilizator mihai995mihai995 mihai995 Data 14 iunie 2012 01:11:59
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#include <fstream>
using namespace std;

const int N = 500005;
int v[N], heap[N], n;

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

inline void sch(int& a, int& b)
{
    int c = a;
    a = b;
    b = c;
}

void up(int x)
{
    while (x > 1 && heap[x] > heap[x/2])
    {
        sch(heap[x], heap[x / 2]);
        x /= 2;
    }
}

void down(int x)
{
    int best = x;
    do
    {
        sch(heap[x], heap[best]);

        x = best;

        if (2 * x <= heap[0] && heap[best] < heap[2 * x])
            best = 2 * x;

        if (2 * x < heap[0] && heap[best] < heap[2 * x + 1])
            best = 2 * x + 1;

    } while (best != x);
}

void push(int x)
{
    heap[++heap[0]] = x;
    up(heap[0]);
}

void pop()
{
    heap[1] = heap[heap[0]--];
    down(1);
}

void heapsort()
{
    for (int i = 1 ; i <= n ; i++)
        push(v[i]);

    for (int i = n ; i ; i--)
    {
        v[i] = heap[1];
        pop();
    }
}

int main()
{
    in >> n;

    for (int i = 1 ; i <= n ; i++)
        in >> v[i];

    heapsort();

    for (int i = 1 ; i <= n ; i++)
        out << v[i] << " ";
    out << "\n";
    return 0;
}