Cod sursa(job #371878)

Utilizator loginLogin Iustin Anca login Data 7 decembrie 2009 17:32:28
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.81 kb
# include <fstream>
using namespace std;
int n, h[500002];
ofstream fout ("algsort.out");

void promoveaza (int k)
{
	int eh=0;
	while (k/2 && !eh)
		if (h[k/2]<=h[k])
			eh=1;
		else
		{
			int aux=h[k/2];
			h[k/2]=h[k], h[k]=aux;
			k/=2;
		}
}

void cerne (int k, int n)
{
	int i, eh=0;
	while (!eh && 2*k<=n)
	{
		i=2*k;
		if (i+1<=n && h[i+1]<h[i])
			i=i+1;
		if (h[k]<=h[i])
			eh=1;
		else
		{
			int aux=h[k];
			h[k]=h[i], h[i]=aux;
			k=i;
		}
	}
}

void read ()
{
	int i;
	ifstream fin ("algsort.in");
	fin>>n;
	for (i=1;i<=n;i++)
	{
		fin>>h[i];
		promoveaza(i);
	}
}

void afis (int k)
{
	int i;
	for (i=k;i>0;i--)	
		fout<<h[i]<<" ";
	fout<<endl;
}

void hs (int n)
{
	int aux;
	for (;n>1;)
	{	
		aux=h[1], h[1]=h[n], h[n]=aux;
		n--;
		cerne(1, n);
	}
}

int main ()
{
	read ();
	hs (n);
	afis (n);
	return 0;
}