Pagini recente » Cod sursa (job #1639176) | Cod sursa (job #1284834) | Cod sursa (job #1085439) | Cod sursa (job #2361532) | Cod sursa (job #282561)
Cod sursa(job #282561)
#include <stdio.h>
#define dim 500100
int n, d[dim], h[dim], poz[dim], k;
void swap(int a, int b)
{
int t=h[a];
h[a]=h[b];
h[b]=t;
}
void sift(int x)
{
int son, rson, lson;
do
{
son=0;
lson=x<<1;
rson=(x<<1)+1;
if (lson<=k) son=lson;
if (rson<=k && d[h[lson]]<d[h[rson]]) son=rson;
if (son && d[h[son]]>d[h[x]])
{
swap(x, son);
poz[h[x]]=x;
poz[h[son]]=son;
x=son;
}
else son=0;
} while (son);
}
void build_heap()
{
int i;
for (i=1; i<=n; i++) poz[i]=i, h[i]=i;
k=n;
for (i=n/2; i; i--) sift(i);
}
void heap_sort()
{
build_heap();
while (k>1)
{
swap(1, k);
poz[h[1]]=1;
poz[h[k]]=-1;
k--;
sift(1);
}
}
int main()
{
int i;
freopen("algsort.in", "r", stdin);
freopen("algsort.out", "w", stdout);
scanf("%d\n", &n);
for (i=1; i<=n; i++) scanf("%d ", &d[i]);
heap_sort();
for (i=1; i<=n; i++) printf("%d ", d[h[i]]);
return 0;
}