Cod sursa(job #1014165)

Utilizator tudorv96Tudor Varan tudorv96 Data 22 octombrie 2013 12:00:48
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
#include <fstream>
#include <iostream>
using namespace std;

int v[500000], n;

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

void down (int x, int n) {
	int val = -1;
	if ((x << 1) <= n)
		val = x << 1;
	if ((x << 1) < n && v[val] < v[(x << 1) + 1])
		val = (x << 1) + 1;
	if (val != -1 && v[val] > v[x])
		swap (v[x], v[val]);
}
	

void reconstruct(int x) {
	int val = -1;
	if ((x << 1) <= n) {
		reconstruct (x << 1);
		val = x << 1;
	}
	if ((x << 1) < n) {
		reconstruct ((x << 1) + 1);
		if (val != -1 && v[(x << 1) + 1] > v[val])
			val = (x << 1) + 1;
		if (val == -1)
			val = (x << 1) + 1;
	}
	if (val > 0 && v[x] < v[val])
		swap (v[x], v[val]);
}

void extract(int &heapsize) {
	swap (v[1], v[heapsize]);
	heapsize--;
	down(1, heapsize);
}		

int main() {
	fin >> n;
	for (int i = 1; i <= n; ++i)
		fin >> v[i];
	reconstruct(1);
	int heapsize = n;
	for (int i = 1; i <= n; ++i)
		extract(heapsize);
	for (int i = 1; i <= n; ++i)
		fout << v[i] << " ";
}