Cod sursa(job #373526)

Utilizator titusuTitus C titusu Data 13 decembrie 2009 23:22:14
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb

using namespace std;
#include <fstream>
#define MAX 500010
int heap[MAX], n;



void read(){
	ifstream fin("algsort.in");
	fin>>n;
	for(int i=1;i<=n;i++)
		fin>>heap[i];
}
void write(){
	ofstream fout("algsort.out");
	for(int i=1;i<=n;++i)
		fout<<heap[i]<<" ";
}

void Cerne(int poz){
	int esteHeap=0,k=poz,i,aux;
	while(!esteHeap && (i=2*k)<=n){
		if(i+1<=n && heap[i]<=heap[i+1])
			i++;
		if(heap[k]>=heap[i])
			esteHeap=1;
		else{
			aux=heap[k]; heap[k] = heap[i]; heap[i] = aux;
			k=i;
		}
	}
}

void Promoveaza(int poz){
	int esteHeap=0, aux, i,k=poz;
	while(!esteHeap && k/2>0){
		i=k/2;
		if(heap[i]>=heap[k])
			esteHeap=1;
		else{
			aux=heap[i]; heap[i] = heap[k]; heap[k]=aux;
			k=i;
		}
	}
}

void sort(){
	for(int i=1;i<=n;i++)
		Promoveaza(i);
	
	int q=n;
	for(  ; n >1 ;){
		int aux=heap[1]; heap[1] = heap[n]; heap[n]=aux;
		n--;
		Cerne(1);
	}
	n=q;
}

int main(){
	read();
	sort();
	write();
	return 0;
}