Cod sursa(job #943124)

Utilizator fhandreiAndrei Hareza fhandrei Data 24 aprilie 2013 14:14:00
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 kb
// Include
#include <fstream>
#include <algorithm>
using namespace std;

// Definitii
#define father node/2
#define leftSon node*2
#define rightSon node*2 + 1

// Constante
const int sz = (int)5e5+1;

// Functii
void checkUp(int node);
void checkDown(int node);

// Variabile
ifstream in("algsort.in");
ofstream out("algsort.out");

int heapSize, num;
int heap[sz];

// Main
int main()
{
	in >> num;
	//for(int i=1 ; i<=num ; ++i)
	while(++heapSize <= num)
	{
		in >> heap[heapSize];
		checkUp(heapSize);
	}
	
	--heapSize;
	
	while(heapSize != 1)
	{
		swap(heap[1], heap[heapSize--]);
		checkDown(1);
	}
	
	for(int i=1 ; i<=num ; ++i)
		out << heap[i] << ' ';
	
	in.close();
	out.close();
	return 0;
}

void checkUp(int node)
{
	if(node==1)
		return;
	
	if(heap[father] < heap[node])
	{
		swap(heap[father], heap[node]);
		checkUp(father);
	}
}

void checkDown(int node)
{
	if(node > heapSize)
		return;
	
	if(rightSon <= heapSize) // are 2 fii
	{
		if(heap[node] < heap[leftSon] && heap[node] < heap[rightSon]) // ambii lui fii sunt mai mari ca el
		{
			if(heap[leftSon] < heap[rightSon]) // cel din dreapta e mai mare
			{
				swap(heap[node], heap[rightSon]);
				checkDown(rightSon);
			}
			else
			{
				swap(heap[node], heap[leftSon]);
				checkDown(leftSon);
			}
			return;
		}
		if(heap[node] < heap[leftSon]) // doar fiul stang e mai mare
		{
			swap(heap[node], heap[leftSon]);
			checkDown(leftSon);
			return;
		}
		if(heap[node] < heap[rightSon]) // doar fiul drept e mai mare
		{
			swap(heap[node], heap[rightSon]);
			checkDown(rightSon);
			return;
		}
		return;
	}
	
	if(leftSon == heapSize) // are un singur fiu
	{
		if(heap[node] < heap[leftSon]) // fiul lui e mai mare
		{
			swap(heap[node], heap[leftSon]);
			checkDown(leftSon);
		}
	}	
}