Cod sursa(job #2270092)

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

using namespace std;

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

int N, heap[500003];

void heapDown(int x, int n) {
    if(2 * x <= n) {
        int st = heap[2 * x], dr = 0;
        if(2 * x + 1 <= n)
            heap[2 * x + 1], dr = heap[2 * x + 1];
        if(st > dr && st > heap[x]) { swap(heap[x], heap[2 * x]);  }
        else if(dr > heap[x]) { swap(heap[x], heap[2 * x + 1]);  }
        heapDown(2 * x, n);
        heapDown(2 * x + 1, n);
    }
}
int main()
{
    f >> N;
    int n = N;
    for(int i = 1; i <= N; i++)
        f >> heap[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;
}