Pagini recente » Cod sursa (job #1891188) | Cod sursa (job #1690652) | Cod sursa (job #985504) | Cod sursa (job #1428357) | Cod sursa (job #1807939)
#include <cstdio>
#include <algorithm>
#define in "algsort.in"
#define out "algsort.out"
#define NMAX (500000 + 7)
using namespace std;
int n, val, H[NMAX], last;
void upHeap(const int &key)
{
int p = key;
while(p != 1)
{
if(H[p] < H[(p>>1)])
{
swap(H[p], H[p>>1]);
p >>= 1;
}
else break;
}
}
void downHeap(const int &key)
{
int p = key;
while(p <= last)
{
if((p<<1) > last) break;
if(((p<<1)|1) > last)
{
if(H[p] <= H[p<<1]) break;
swap(H[p], H[(p<<1)]);
p = (p<<1);
continue;
}
if(H[((p<<1)|1)] < H[(p<<1)])
{
if(H[p] <= H[((p<<1)|1)]) break;
swap(H[p], H[((p<<1)|1)]);
p = ((p<<1)|1);
continue;
}
if(H[p] <= H[(p<<1)]) break;
swap(H[p], H[(p<<1)]);
p = (p<<1);
}
}
void hPush(const int &value)
{
H[++last] = value;
upHeap(last);
}
void hPop()
{
swap(H[1], H[last--]);
downHeap(1);
}
int main()
{
freopen(in, "r", stdin);
freopen(out, "w", stdout);
scanf("%d", &n);
for(int i = 1; i<= n; ++i)
{
scanf("%d", &val);
hPush(val);
}
while(last)
{
printf("%d ", H[1]);
hPop();
}
printf("\n");
return 0;
}