Cod sursa(job #1249007)

Utilizator ArkinyStoica Alex Arkiny Data 26 octombrie 2014 12:57:02
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
#include<fstream>
using namespace std;

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

unsigned long heap[500001];
long N,k;

void move_up(int pos)
{
	while(pos>1 && heap[pos]<heap[pos/2])
	{
		swap(heap[pos],heap[pos/2]);
		pos=pos/2;
	}
}

void move_down(int pos)
{
	int child;
	do
	{
		child=0;
		if((pos*2+1)<=k && (heap[pos]>heap[pos*2] || heap[pos]>heap[pos*2+1]))
			child=(heap[pos*2]<heap[pos*2+1]) ? pos*2:(pos*2+1);
		else if(pos*2 <= k && heap[pos]>heap[pos*2])
			child=pos*2;

		if(child)
		{
			swap(heap[pos],heap[child]);
			pos=child;
		}
	}while(child);
		 
}

void add_to_heap(unsigned long value)
{
	  heap[++k]=value;
	  move_up(k);
}

void heapsort()
{
	while(k>=1)
	{
		out<<heap[1]<<" ";
		swap(heap[1],heap[k--]);
		move_down(1);
	}
}

int main()
{
	in>>N;
	unsigned long j;
	for(int i=1;i<=N;i++)
	{
		in>>j;
		add_to_heap(j);
	}
	heapsort();
	in.close();
	out.close();
	return 0;
}