Pagini recente » Cod sursa (job #1910147) | Cod sursa (job #1136179) | Cod sursa (job #2706903) | Cod sursa (job #2791101) | Cod sursa (job #495408)
Cod sursa(job #495408)
#include <stdio.h>
const int maxn=500001;
long int v[maxn];
int i,N;
void swap(long int *a,long int *b)
{
long int aux;
aux=*a;
*a=*b;
*b=aux;
}
void upheap(int k)
{
while(k>1 && v[k]>v[k/2])
{
swap(&v[k],&v[k/2]);
k/=2;
}
}
void downheap(int k,int N)
{
int son;
do
{
son=0;
if(2*k<=N)
{
son=2*k;
if(2*k+1<=N && v[son]<v[2*k+1])
son=2*k+1;
if(v[son]<v[k]) son=0;
}
if(son)
{
swap(&v[k],&v[son]);
k=son;
}
}
while(son);
}
int main()
{
int hp;
freopen("algsort.in","r",stdin);
freopen("algsort.out","w",stdout);
scanf("%d",&N);
for(i=1;i<=N;i++) scanf("%ld ",&v[i]);
for(i=N;i>=2;i--) upheap(i);
hp=N;
while(hp)
{
swap(&v[1],&v[hp]);
hp--;
downheap(1,hp);
}
for(i=1;i<=N;i++) printf("%ld ",v[i]);
}