Cod sursa(job #1441830)

Utilizator buzu.tudor67Tudor Buzu buzu.tudor67 Data 24 mai 2015 12:51:37
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include<fstream>
using namespace std;
ifstream fi("algsort.in");
ofstream fo("algsort.out");

const int MAX_N = 500005;

int i,n,x,h[MAX_N],heap_size;


void down_heap(int k){
	 int son=1;
	 
	 while(son)
	 	if(2*k<=heap_size){
	 		 son=2*k;
	 		 if(2*k+1<=heap_size && h[2*k+1]<h[2*k]){
	 			son=2*k+1;
			 }
			 
			 if(h[son]<h[k]){
			 	swap(h[son],h[k]);
			 	k=son;
			 }else son=0;
			 
		 }else son=0;
	 
}

void up_heap(int k){
	 while(k>1 && h[k/2]>h[k]){
	 	swap(h[k],h[k/2]);
	 	k/=2;
	 }
}

void insert_heap(int x, int &heap_size){
	 h[++heap_size]=x;
	 up_heap(heap_size);
}

void delete_heap(int k, int &heap_size){
	 h[1]=h[heap_size--];
	 down_heap(1);
}


int main(){
	fi>>n;
	for(i=1;i<=n;i++){
		fi>>x;
		insert_heap(x, heap_size);
	}
	
	for(i=1;i<=n;i++){
		fo<<h[1]<<" ";
		delete_heap(1, heap_size);
	}
	
	fi.close();
	fo.close();
	return 0;
}