Cod sursa(job #3277006)

Utilizator mlupseLupse-Turpan Mircea mlupse Data 15 februarie 2025 11:14:08
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <fstream>
using namespace std;
ifstream fin("algsort.in");
ofstream fout("algsort.out");
const int NMax = 500000;
int N, NHeap;
int X[NMax + 5], Heap[NMax + 5];
void Read()
{
    fin >> N;
    for(int i = 1 ; i <= N; ++i)
        fin >> X[i];
}

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

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

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


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

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

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