Cod sursa(job #1012606)

Utilizator dunhillLotus Plant dunhill Data 19 octombrie 2013 13:22:58
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.73 kb
#include <fstream>
#include <cstring>
#include <algorithm>
using namespace std;

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

int i, N;
int v[500001], H[500001];

void UP_heap(int u) {
	while (u != 1 && H[u] < H[u / 2]) swap(H[u / 2], H[u]), u /= 2;
}

void DOWN_heap(int u) {
	swap(H[1], H[N]);
	--N;
	while (u * 2 <= N) {
		if (u * 2 + 1 <= N) {
			if (H[u * 2] < H[u * 2 + 1]) 
				swap(H[u], H[u * 2]), u *= 2;
			else 
				swap(H[u], H[u * 2 + 1]), u = u * 2 + 1;
		}
		else 
			swap(H[u], H[u * 2]), u *= 2;
	}
}

int main() {
	fin >> N;
	for (i = 1; i <= N; ++i) {
		fin >> H[i];
		UP_heap(i);
	}
	while (N) {
		fout << H[1] << ' ';
		DOWN_heap(1);
	}
	fout << '\n';
	return 0;
}