Cod sursa(job #2082521)

Utilizator alex2209alexPavel Alexandru alex2209alex Data 6 decembrie 2017 14:18:38
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <fstream>

using namespace std;
ifstream f("algsort.in");
ofstream g("algsort.out");
int heap[500001],n,m,i,a;
void add(int val)
{
    heap[++n]=val;
    int pos=n;
    while(pos!=1 && heap[pos]<heap[pos/2])
    {
        swap(heap[pos],heap[pos/2]);
        pos=pos/2;
    }
}
void erase1(int pos)
{
    swap(heap[1],heap[n]);
    n--;
    while(pos<=n)
    {
        int mx=heap[pos],best=0;
        if(2*pos<=n && mx>heap[2*pos])
        {
            mx=heap[2*pos];
            best=1;
        }
        if(2*pos+1<=n && mx>heap[2*pos+1])
        {
            mx=heap[2*pos+1];
            best=2;
        }
        if(best==0)
        {
            break;
        }
        else if(best==1)
        {
            swap(heap[pos],heap[pos*2]);
            pos=pos*2;
        }
        else
        {
            swap(heap[pos],heap[pos*2+1]);
            pos=pos*2+1;
        }
    }
}
int main()
{
    f>>m;
    for(i=1;i<=m;i++)
    {
        f>>a;
        add(a);
    }
    while(m>0)
    {
        g<<heap[1]<<" ";
        erase1(1);
        m--;
    }
    return 0;
}