Cod sursa(job #2270099)

Utilizator alexsandulescuSandulescu Alexandru alexsandulescu Data 27 octombrie 2018 09:08:58
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include <fstream>
#include <algorithm>

using namespace std;

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

int N, x, heap[500004];

void heapDown(int x, int n) {
    if(2 * x <= n) {
        int st = heap[2 * x], dr = st - 1;
        if(2 * x + 1 <= n)
            dr = heap[2 * x + 1];
        if(st > dr && st > heap[x]) { swap(heap[x], heap[2 * x]); heapDown(2 * x, n); }
        else if(dr > heap[x]) { swap(heap[x], heap[2 * x + 1]); heapDown(2 * x + 1, n); }
    }
}

void heapUp(int x) {
    if(x > 1) {
        if(heap[x] > heap[x / 2])
            swap(heap[x], heap[x / 2]);
        heapUp(x / 2);
    }
}
int main()
{
    f >> N;
    int n = N;
    for(int i = 1; i <= N; i++)
        f >> x, heap[i] = x, heapUp(i);
    for(int i = 1; i <= N; i++) {
        heapDown(1, n);
        swap(heap[1], heap[n]);
        n--;
    }
    for(int i = 1; i <= N; i++)
        g << heap[i] << " ";
    g << "\n";
    return 0;
}