Cod sursa(job #1575668)

Utilizator cordun_cristinaCristina Maria Cordun cordun_cristina Data 21 ianuarie 2016 18:22:38
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include <fstream>
using namespace std;

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

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

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

void Upheap(int Nod)
{
    int Tata = Nod / 2;

    if(Tata && Heap[Tata]>Heap[Nod])
        {
            swap(Heap[Nod],Heap[Tata]);
            Upheap(Tata);
        }
}

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

void DownHeap(int Nod)
{
    int Son = 2*Nod;

    if(Son > NHeap)
        return;

    if(Son == NHeap && Heap[Son] < Heap[Nod])
        {
            swap(Heap[Son],Heap[Nod]);
            return;
        }

    if(Heap[Son] < Heap[Son+1])
        {
            if(Heap[Son] < Heap[Nod])
                {
                    swap(Heap[Son], Heap[Nod]);
                    DownHeap(Son);
                }
        }
    else
        {
            if(Heap[Son+1] < Heap[Nod])
                {
                    swap(Heap[Son+1], Heap[Nod]);
                    DownHeap(Son+1);
                }
        }


}

void Sort()
{
    BuildHeap();

    for(int i = 1; i<=N; i++)
        {
            X[i] = Heap[1];
            Heap[1] = Heap[NHeap--];
            DownHeap(1);
        }
}

void Print()
{
    for(int i = 1; i<=N; i++)
        fout<<X[i]<<" ";
}

int main()
{
    Read();
    Sort();
    Print();
    return 0;
}