Cod sursa(job #1519865)

Utilizator jimcarterJim Carter jimcarter Data 7 noiembrie 2015 22:28:08
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <cstdio>
#include <algorithm>
using namespace std;

FILE *f = fopen ( "algsort.in" , "r" ) , *g = fopen ( "algsort.out" , "w" );

const int MAX = 500005;
int Size , myInts [ MAX ] , i , left , right , son , index , aux;

void read()
{
    fscanf ( f , "%d" , &Size );
    for ( i = 1 ; i <= Size ; i ++ )
        fscanf ( f , "%d" , &myInts [ i ] );
}

void heapify ( int index )
{
	son = -1;
	while ( index != son )
	{
		left = index * 2 , right = left + 1;
		son = index;
		if ( left <= Size && myInts [ left ] < myInts [ index ] )
			index = left;
		if ( right <= Size && myInts [ right ] < myInts [ index ] )
			index = right;
		aux = myInts [ index ] , myInts [ index ] = myInts [ son ] , myInts [ son ] = aux;
	}
}

void build_heap()
{
	for ( i = Size / 2 ; i > 0 ; i -- )
		heapify ( i );
}

void heapsort()
{
	build_heap();
}

void eliminate ( int index )
{
	myInts [ 1 ] = myInts [ Size ] , Size --;
	heapify ( 1 );
}

void print()
{
    while ( Size )
    {
        fprintf ( g , "%d " , myInts [ 1 ] );
        eliminate ( 1 );
    }
}

int main()
{
    read();
    heapsort();
    print();
    return 0;
}