Cod sursa(job #2123885)

Utilizator epermesterNagy Edward epermester Data 6 februarie 2018 18:21:26
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.71 kb
#include<fstream>
#include<vector>
using namespace std;
int n;		//

void heapify(vector<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() {
	ifstream in("algsort.in");
	ofstream out("algsort.out");
	in >> n;
	vector<int> x;
	x.push_back(0);
	for (int i = 1;i <= n;++i) {
		int temp;
		in >> temp;
		x.push_back(temp);
	}
	for (int i = n / 2;i > 0;--i)
		heapify(x, i);
	while(n>1) {
		int aux = x[n];
		x[n] = x[1];
		x[1] = aux;
		out << x.back() << " ";
		x.pop_back();
		n--;
		if(n>1) heapify(x, 1);
	}
	out << x.back();
}