Cod sursa(job #1090277)

Utilizator fhandreiAndrei Hareza fhandrei Data 22 ianuarie 2014 15:41:51
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
// Include
#include <fstream>
using namespace std;

// Definitii
#define father (node>>1)
#define leftSon (node<<1)
#define rightSon (node<<1)+1

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

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

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

int num, heapSize;
int heap[sz];

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

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

void checkDown(int node)
{
	if(heapSize < node)
		return;
	
	if(rightSon <= heapSize)
	{
		if(heap[node] < heap[leftSon] && heap[node] < heap[rightSon])
		{
			if(heap[leftSon] <= heap[rightSon])
			{
				swap(heap[node], heap[rightSon]);
				checkDown(rightSon);
			}
			else
			{
				swap(heap[node], heap[leftSon]);
				checkDown(leftSon);
			}
			return;
		}
		
		if(heap[node] < heap[leftSon])
		{
			swap(heap[node], heap[leftSon]);
			checkDown(leftSon);
		}
		
		if(heap[node] < heap[rightSon])
		{
			swap(heap[node], heap[rightSon]);
			checkDown(rightSon);
		}
	}
	
	if(leftSon == heapSize)
	{
		swap(heap[node], heap[leftSon]);
		checkDown(leftSon);
		return;
	}
}