Cod sursa(job #787380)

Utilizator space.foldingAdrian Soucup space.folding Data 13 septembrie 2012 11:45:33
Problema Sortare prin comparare Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include <cstdio>
#include <algorithm>
using namespace std;

int h[500001], n;

void insert_heap(int *h, int &hSize, int elem)
{
	h[hSize] = elem;

	int parent = hSize / 2, child = hSize;

	hSize++;

	while(parent >= 1)
	{
		if(h[parent] > h[child])
		{
			swap(h[parent], h[child]);
			child = parent;	
			parent /= 2;					
		}
		else
			parent = 0;	
	}
}


int pop_heap(int *h, int &hSize)
{
	int result = h[1];
	int parent = 1, child = 2;
	h[1] = h[hSize-1];
	hSize--;

	while(child < hSize - 1)
	{
		if(h[child] > h[child+1])
			child++;
		if(h[child] < h[parent])
		{
			swap(h[child], h[parent]);
			parent = child;
			child = parent * 2;
		}
		else
		{
			child = hSize;
		}
	}

	return result;
}


int main ()
{
#ifndef ONLINE_JUDGE
	freopen("algsort.in", "r", stdin);
	freopen("algsort.out", "w", stdout);
#endif

	scanf("%d", &n);
	


	int current, hSize = 1;


	for(int i=0; i<n; ++i)
	{
		scanf("%d", &current);
		insert_heap(h, hSize, current);
	}

	for(int i=0; i<n; ++i)
	{
		printf("%d ", pop_heap(h, hSize));		
	}
	return 0;
}