Cod sursa(job #615397)

Utilizator moonbeamElma Moonbeam moonbeam Data 9 octombrie 2011 17:06:30
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.77 kb
#include<cstdio>
#include<queue>
using namespace std;
#define NM 500001
int h[NM],N;
void cobor(int k)
{
	int son;
	while (true)
	{
		son=k;
		if ((k<<1)<=N && h[k]<h[k<<1])
		{
			son=(k<<1);
			if (son+1<=N && h[son]<h[son+1])
				++son;
		}
		if (son==k)
			return;
		int aux=h[k];
		h[k]=h[son];
		h[son]=aux;
		k=son;
	}
}
void heapsort()
{
	for (int i=N>>1; i>0; --i)
		cobor(i);
	while (N>1)
	{
		int aux=h[N];
		h[N]=h[1];
		h[1]=aux;
		--N;
		cobor(1);
	}
}
void afis(int N)
{
	for (int i=1; i<=N; ++i)
		printf("%d ",h[i]);
}
int main()
{
	freopen("algsort.in","r",stdin);
	freopen("algsort.out","w",stdout);
	scanf("%d",&N);
	int CN=N;
	for(int i=1; i<=N; ++i)
		scanf("%d",&h[i]);
	heapsort();
	
	afis(CN);
	return 0;
}