Cod sursa(job #495407)

Utilizator PlayLikeNeverB4George Marcus PlayLikeNeverB4 Data 25 octombrie 2010 00:47:38
Problema Sortare prin comparare Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 0.81 kb
#include <stdio.h>

const int maxn=500001;

long int v[maxn];
int i,N;

void swap(long int *a,long int *b)
{
	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]);
}