Pagini recente » Cod sursa (job #1730268) | Cod sursa (job #1998245) | Cod sursa (job #1858966) | Cod sursa (job #2425469) | Cod sursa (job #1849112)
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
int heap [500005],n;
ifstream fin("algsort.in");
ofstream fout("algsort.out");
void pushHeap(int x)
{
int k;
heap[++n] = x;
k=n;
while(heap[k]<heap[k/2]&&k>1)
{
swap(heap[k],heap[k/2]);
k/=2;
}
}
int popHeap()
{
int x = heap[1];
heap[1]=heap[n];
n--;
int k=1;
while(2*k<=n)
{
if(2*k==n)
{
swap(heap[k],heap[2*k]);
k=2*k;
continue;
}
if(heap[2*k]<heap[2*k+1])
{
swap(heap[k],heap[2*k]);
k=2*k;
}
else
{
swap(heap[k],heap[2*k+1]);
k=2*k+1;
}
}
return x;
}
int main()
{
int x,nr;
fin>>nr;
for(int i=1;i<=nr;i++)
{
fin>>x;
pushHeap(x);
}
for(int i=1;i<=nr;i++)
{
fout<<popHeap()<<" ";
}
return 0;
}