Pagini recente » Cod sursa (job #3252586) | Cod sursa (job #1629782) | Cod sursa (job #2586507) | Cod sursa (job #847180) | Cod sursa (job #2950077)
#include <iostream>
#include <fstream>
#include <cstdlib>
#define NMAX 500000
using namespace std;
ifstream fin("algsort.in");
ofstream fout("algsort.out");
int v[NMAX];
int lomutoPartition(int lo, int hi) {
int tmp;
int pivotIndex = lo + rand() % (hi - lo + 1);
int curr = lo - 1;
tmp = v[pivotIndex], v[pivotIndex] = v[hi], v[hi] = tmp;
int pivot = v[hi];
for (int i = lo; i < hi; ++i) {
if (v[i] <= pivot) {
// increment curr and swap a[i] with a[curr]
++curr;
tmp = v[i], v[i] = v[curr], v[curr] = tmp;
}
}
tmp = v[curr + 1], v[curr + 1] = v[hi], v[hi] = tmp;
return curr + 1;
}
void quickSort(int lo, int hi) {
if (lo < hi) {
int pivotIndex = lomutoPartition(lo, hi);
quickSort(lo, pivotIndex - 1);
quickSort(pivotIndex + 1, hi);
}
}
int main()
{
ios_base::sync_with_stdio(false);
fin.tie(NULL);
fout.tie(NULL);
int n;
fin >> n;
for (int i = 0; i < n; ++i) {
fin >> v[i];
}
quickSort(0, n - 1);
for (int i = 0; i < n; ++i) {
fout << v[i] << " ";
}
}