Pagini recente » Cod sursa (job #2281319) | Cod sursa (job #2193599) | Cod sursa (job #2361061) | Cod sursa (job #3133689) | Cod sursa (job #1849118)
#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],mnm,pzmnm;
heap[1]=heap[n];
n--;
int k=1;
while(2*k<=n)
{
if(2*k==n)
{
mnm=heap[2*k];
pzmnm=2*k;
}
else
{
if(heap[2*k]<=heap[2*k+1])
{
mnm=heap[2*k];
pzmnm=2*k;
}
else
{
mnm=heap[2*k+1];
pzmnm=2*k+1;
}
}
if(heap[k]>=mnm)
{
swap(heap[k],heap[pzmnm]);
k=pzmnm;
}
else
break;
}
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;
}