Cod sursa(job #3359782)

Utilizator robert.stefanRobert Stefan robert.stefan Data 3 iulie 2026 22:05:11
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include<fstream>

using namespace std;

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

// Sortare folosind min heap

// Complexitate: O(n log n), deoarece, pentru fiecare element din heap, 
// extragerea lui are complexitate O(log n).

int main() {
	int n, heap[500000];

	fin >> n;

	fin >> heap[0];

	for(int i = 1; i < n; i++) {
		fin >> heap[i];

		// shift up

		int fiu = i;

		while(fiu > 0) {
			int tata = (fiu - 1) / 2;
			
			if(heap[fiu] < heap[tata]) {
				int aux = heap[fiu];
				heap[fiu] = heap[tata];
				heap[tata] = aux;

				fiu = tata;
			} else {
				break;
			}
		}
	}

	int lenHeap = n;

	for(int i = 0; i < n; i++) {
		fout << heap[0] << " ";

		// sterg elementul din heap
		heap[0] = heap[lenHeap - 1];
		lenHeap--;

		// shift down

		int parinte = 0;

		while(2 * parinte + 1 < lenHeap) { // am cel putin un fiu
			int fiuMin = 2 * parinte + 1;

			if(2 * parinte + 2 < lenHeap && heap[2 * parinte + 2] < heap[fiuMin]) {
				fiuMin = 2 * parinte + 2;
			}

			if(heap[parinte] <= heap[fiuMin]) {
				break;
			}

			int aux = heap[parinte];
			heap[parinte] = heap[fiuMin];
			heap[fiuMin] = aux;

			parinte = fiuMin;
		}
	}
	
	fout << "\n";

	return 0;
}