Cod sursa(job #2286460)

Utilizator AlexAxeToporan Victor AlexAxe Data 20 noiembrie 2018 12:09:52
Problema Sortare prin comparare Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream in("algsort.in");
ofstream out("algsort.out");

const int NMax = 1e5;
int N, NHeap, X[NMax], Heap[NMax];

void Read(){
    in >> N;
    for (int i = 1; i <= N; ++i)
        in >> X[i];
}

void DownHeap(int Nod){
    int Son1 = Nod * 2;
    int Son2 = Nod * 2 + 1;
    if (Son1 > NHeap)
        return;
    if (Son1 == NHeap){
        if (Heap[Nod] > Heap[Son1])
            swap(Heap[Nod], Heap[Son1]);
        return;
    }
    if (Heap[Son1] < Heap[Son2]){
        if (Heap[Nod] > Heap[Son1]){
            swap(Heap[Nod], Heap[Son1]);
            DownHeap(Son1);
        }
    }
    else
        if (Heap[Nod] > Heap[Son2]){
            swap(Heap[Nod], Heap[Son2]);
            DownHeap(Son2);
        }
}

void UpHeap(int Nod){
    int Father = Nod / 2;
    if (Heap[Nod] < Heap[Father] && Father){
        swap(Heap[Nod], Heap[Father]);
        UpHeap(Father);
    }
}

void BuildHeap(){
    for (int i = 1; i <= N; ++i){
        Heap[i] = X[i];
        UpHeap(i);
    }
    NHeap = N;
}

void HeapSort(){
    while (NHeap){
        out << Heap[1] << " ";
        Heap[1] = Heap[NHeap--];
        DownHeap(1);
    }
    out << '\n';
}

int main(){
    Read();
    BuildHeap();
    HeapSort();
    return 0;
}