Cod sursa(job #2844718)

Utilizator Theo14Ancuta Theodor Theo14 Data 5 februarie 2022 10:52:39
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include<bits/stdc++.h>
using namespace std;

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

int heap[500002],n,x,n_heap;

void add(int value)
{
    n_heap++;
    heap[n_heap]=value;
    int current=n_heap;
    while(current>1 && heap[current]<heap[current/2])
    {
        swap(heap[current],heap[current/2]);
        current/=2;
    }
}

void removee()
{
    heap[1]=heap[n_heap];
    heap[n_heap]=0;
    n_heap--;
    int current=1,chosen_son,ok=1;
    do
    {
        ok=0;
        chosen_son=current;
        if(current*2<=n_heap && heap[current*2]<heap[chosen_son])
            chosen_son=current*2;
        if(current*2+1<=n_heap && heap[current*2+1]<heap[chosen_son])
            chosen_son=current*2+1;
        if(chosen_son!=current)
        {
            swap(heap[chosen_son],heap[current]);
            current=chosen_son;
            ok=1;
        }

    }while(ok==1);
}

int main()
{
    int i;
    f>>n;
    for(i=1;i<=n;i++)
    {
        f>>x;
        add(x);
    }
    for(i=1;i<=n;i++)
    {
        g<<heap[1]<<" ";
        removee();
    }
    return 0;
}