Cod sursa(job #2270085)

Utilizator stefantagaTaga Stefan stefantaga Data 27 octombrie 2018 08:56:58
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <fstream>

using namespace std;
ifstream f("algsort.in");
ofstream g("algsort.out");
int heap[500001];
void heapup(int x)
{
    if (x>1)
    {
        if (heap[x]>heap[x/2])
        {
            swap(heap[x],heap[x/2]);
            heapup(x/2);
        }
    }
}
void heapdown(int x,int u)
{
    int st,dr;
    if (2*x<=u)
    {
        st=heap[2*x];
        if (2*x+1<=u)
        {
            dr=heap[2*x+1];
        }
        else
        {
            dr=st-1;
        }
        if (max(st,dr)>heap[x])
        {
            if (st>dr)
            {
                swap(heap[x],heap[2*x]);
                heapdown(2*x,u);
            }
            else
            {
                swap(heap[x],heap[2*x+1]);
                heapdown(2*x+1,u);
            }
        }
    }
}
int of[500001],n,i,x,lung;
int main()
{
    f>>n;
    for (i=1;i<=n;i++)
    {
        f>>x;
        heap[i]=x;
        heapup(i);
    }
    lung=n;
    for (i=1;i<=n;i++)
    {
        of[lung]=heap[1];
        swap(heap[1],heap[lung]);
        lung--;
        heapdown(1,lung);
    }
    for (i=1;i<=n;i++)
    {
        g<<of[i]<<" ";
    }
    return 0;
}