Cod sursa(job #2123873)

Utilizator epermesterNagy Edward epermester Data 6 februarie 2018 18:11:28
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.61 kb
#include<fstream>

int n;

void heapify(int *x, int i) {
	int j = i * 2;
	if (i * 2 + 1 <= n && x[i * 2 + 1] < x[i * 2])
		j = i * 2 + 1;
	if (x[i] > x[j]) {
		int aux = x[j];
		x[j] = x[i];
		x[i] = aux;
	}
	if(j<=n/2) heapify(x, j);
}

int main() {
	std::ifstream in("algsort.in");
	std::ofstream out("algsort.out");
	in >> n;
	int *x = new int[n+1];
	for (int i = 1;i <= n;++i)
		in >> x[i];
	for (int i = n / 2;i > 0;--i)
		heapify(x, i);
	int k = n;
	while(n>1) {
		int aux = x[n];
		x[n] = x[1];
		x[1] = aux;
		out << x[n] << " ";
		n--;
		if(n>1) heapify(x, 1);
	}
	out << x[n];
}