Cod sursa(job #2760183)

Utilizator dey44andIoja Andrei-Iosif dey44and Data 23 iunie 2021 15:19:48
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>

using namespace std;

int N, heap[500005], M;

ifstream cin("algsort.in");
ofstream cout("algsort.out");

void Insereaza(int x)
{
    N++;
    heap[N] = x;
    int son = N, father = N / 2;
    while(father >= 1)
    {
        if(heap[son] > heap[father])
        {
            swap(heap[son], heap[father]);
            son = father;
            father = father / 2;
        }
        else father = 0;
    }
}

int Sterge()
{
    int x = heap[1];
    heap[1] = heap[N];
    N--;
    int father = 1, son = father * 2;
    while(son <= N)
    {
        if(son < N && heap[son + 1] > heap[son])
        {
            son = son + 1;
        }
        if(heap[son] > heap[father])
        {
            swap(heap[son], heap[father]);
            father = son;
            son = son * 2;
        }
        else son = N + 1;
    }
    return x;
}

int main()
{
    cin >> M;
    for(int i = 1; i <= M; i++)
    {
        int x;
        cin >> x;
        Insereaza(x);
    }

    for(int i = 1; i < M; i++)
    {
        int x = Sterge();
        heap[N + 1] = x;
    }
    for(int i = 1; i <= M; i++)
        cout << heap[i] << " ";

    return 0;
}