Cod sursa(job #807218)

Utilizator MtkMarianHagrSnaf MtkMarian Data 4 noiembrie 2012 13:27:42
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include<cstdio>
#include<algorithm>
using namespace std ;
#define NMAX 500005
int vheap[ NMAX ]  , n , ln_heap = 0 ;
void ins_heap ( int x )
{
	++ln_heap ;
	int ln = ln_heap ;
	vheap[ ln_heap ] = x ;
	while ( ln /2 >= 1 )
	{
		if( vheap [ ln/2 ] > vheap [ ln ] )
			swap ( vheap [ ln/2 ] , vheap [ ln ] );

		ln /= 2 ;
	}
}

int elim_heap (  )
{
	int y = vheap [ 1 ];
	
	if ( ln_heap >=3 )
	{
		swap(vheap [ ln_heap ] , vheap [ 1 ] );

		--ln_heap ;
		int ln = 1;
		

		while ( ln*2 <= ln_heap )
		{
			int j = ln *2 ;

			if( j < ln_heap ) if( vheap [ j ] > vheap [ j+1 ] ) ++j ;

			if( vheap [ ln ] > vheap [ j ] ) 
			{
				swap ( vheap[ ln ] , vheap [ j ] ) ;
				ln =  j ;
			}
			else break ;
		


		}
	}
	else 
	if( ln_heap == 2  )
	{
		swap(vheap [ ln_heap ] , vheap [ 1 ] );
		--ln_heap ;
	}
	return y ;
	
}

int main()
{
	freopen("algsort.in" , "r" , stdin);
	freopen("algsort.out" , "w" , stdout); 
	scanf("%d",&n);
	int x ;
	for (int i = 1 ; i <=n ; ++i  )
	{
		scanf("%d", &x) ;
		ins_heap( x );
	}

	

	for (int i=1 ;i <= n; ++i)		
	{
		printf("%d " ,elim_heap () );
		
	}

	
	

	return 0;
}