Cod sursa(job #2636605)

Utilizator irimia_alexIrimia Alex irimia_alex Data 18 iulie 2020 19:53:05
Problema Sortare prin comparare Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 kb
#include <fstream>
#include <ctime>
#define NMAX 500005

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

int v[NMAX], n;

void swap(int& a, int& b) {
	int aux = a;
	a = b;
	b = aux;
}

void heapify(int i) {
	int min = i, left = 2 * i, right = 2 * i + 1;
	if (left <= n && v[left] < v[min])
		min = left;
	if (right <= n && v[right] < v[min])
		min = right;
	if (min == i) return;
	swap(v[i], v[min]);
	heapify(min);
}

void heapSort() {
	for (int i = n / 2;i >= 1;--i)
		heapify(i);
	for (int i = 1;i <= n;++i) {
		fout << v[1] << ' ';
		swap(v[1], v[n--]);
		heapify(1);
	}
}

int main() {
	std::ios::sync_with_stdio(false);

	fin >> n;
	for (int i = 1;i <= n;++i)
		fin >> v[i];
	
	clock_t t = clock();
	heapSort();
	printf("%f", (float)(clock() - t) / CLOCKS_PER_SEC);

	for (int i = 1;i <= n;++i)
		fout << v[i] << ' ';

	

	return 0;
}