Cod sursa(job #3206225)

Utilizator mihai_zegheruZegheru Mihai mihai_zegheru Data 21 februarie 2024 23:28:46
Problema Sortare prin comparare Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;

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

const int MAX_N = 500005;

int n;
int v[MAX_N];

int Partition(int v[], int lf, int rg, int pivotVal) {
	int lowerPos = lf - 1;

	for (int i = lf; i < rg; i++) {
		if (v[i] < pivotVal) {
			lowerPos++;
			swap(v[lowerPos], v[i]);
		}
	}

	lowerPos++;
	swap(v[lowerPos], v[rg]);

	return lowerPos;
}

void QSort(int v[], int lf, int rg) {
	if (lf >= rg) {
		return;
	}

	int pivotIdx = lf + (rand() % (rg - lf + 1));
	int pivotVal = v[pivotIdx];
	swap(v[pivotIdx], v[rg]);

	int partPos = Partition(v, lf, rg, pivotVal);

	QSort(v, lf, partPos - 1);
	QSort(v, partPos + 1, rg);
}

int main() {
	srand(time(0));

	fin >> n;

	// indexed from 1
	for (int i = 1; i <= n; i++) {
		fin >> v[i];
	}

	QSort(v, 1, n);

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