Cod sursa(job #2618176)

Utilizator radustn92Radu Stancu radustn92 Data 23 mai 2020 20:05:21
Problema Sortare prin comparare Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <queue>
#include <cstdlib>
#include <ctime>
using namespace std;

const int NMAX = 500505;
int N, A[NMAX], copyA[NMAX];

void sortArray(int A[], int from, int to) {
	if (to - from <= 0) {
		return;
	}
	int pivotIdx = from + rand() % (to - from + 1);

	// no constant space
	int leftIdx = from, rightIdx = to;

	for (int idx = from; idx <= to; idx++) {
		if (idx == pivotIdx) {
			continue;
		}
		if (A[idx] <= A[pivotIdx]) {
			copyA[leftIdx++] = A[idx];
		} else {
			copyA[rightIdx--] = A[idx];
		}
	}
	copyA[leftIdx] = A[pivotIdx];

	for (int idx = from; idx <= to; idx++) {
		A[idx] = copyA[idx];
	}

	// copy(copyA + from, copyA + to + 1, A + from);
	sortArray(A, from, leftIdx - 1);
	sortArray(A, leftIdx + 1, to);
}

int main() {
	freopen("algsort.in", "r", stdin);
	freopen("algsort.out", "w", stdout);

	srand(time(0));

	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	cin >> N;
	for (int idx = 1; idx <= N; idx++) {
		cin >> A[idx];
	}

	sortArray(A, 1, N);
	for (int idx = 1; idx <= N; idx++) {
		if (idx > 1) {
			cout << " ";
		}
		cout << A[idx];
	}
	cout << "\n";
	return 0;
}