Cod sursa(job #2296399)

Utilizator livliviLivia Magureanu livlivi Data 4 decembrie 2018 17:25:50
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include<fstream>
#include<vector>
using namespace std;
 
ifstream cin("algsort.in");
ofstream cout("algsort.out");

vector<int> heap;

void pushHeap(int x){
	heap.push_back(x);
 
	int p = heap.size() - 1;
	while(p > 0){
		if (heap[p] < heap[(p - 1) / 2]){
			swap(heap[p], heap[(p - 1) / 2]);
			p = (p - 1) / 2;
		}
		else break;
	}
}

void popHeap(){
	swap(heap[0], heap.back());
	heap.pop_back();
 
	int p = 0;
	while(p < heap.size()){
		int fiu = p;
 
		if (p * 2 + 1 < heap.size() && heap[p * 2 + 1] < heap[fiu]){
			fiu = 2 * p + 1;
		}
		if (p * 2 + 2 < heap.size() && heap[p * 2 + 2] < heap[fiu]){
			fiu = p * 2 + 2;
		}
 
		if (fiu == p) break;
 
		swap(heap[p], heap[fiu]);
		p = fiu;
	}
}

int topHeap(){
	if (!heap.empty()) return heap[0];
	else return -1;
}

int main(){
	int n;
	cin >> n;

	for(int i = 1; i <= n; i++){
		int x;
		cin >> x;
		pushHeap(x);
	}

	for(int i = 1; i <= n; i++){
		cout << topHeap() << ' ';
		popHeap();
	}

	cout << endl;
	return 0;
}