Cod sursa(job #1744200)

Utilizator whoasdas dasdas who Data 19 august 2016 14:16:37
Problema Sortare prin comparare Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#define IA_PROB "algsort"

#include <cassert>
#include <cstdio>
#include <cstring>

#include <iostream>
#include <fstream>

#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>

#include <algorithm>

using namespace std;

static inline int rand_int(int l, int r) {
	assert(l < r);
	return l + random() % (r - l);
}

void my_qsort_impl(int *v, int l, int r) {
	if (r - l <= 1) return;
	swap(v[l], v[rand_int(l, r)]); // select random pivot and bring it to position l
	int lle_idx = l; // index of last (rightmost) element that's less than or equal to the pivot
	for (int i = l + 1; i < r; i++) {
		if (v[i] <= v[l]) { //le
			lle_idx++;
			swap(v[i], v[lle_idx]);
		}
	}
	swap (v[l], v[lle_idx]); // bring pivot to its final position
	my_qsort_impl(v, l, lle_idx); // don't include the pivot (otherwise we'd risk entering an infinite loop)
	my_qsort_impl(v, lle_idx + 1, r); // again, don't include the pivot
}

void my_qsort(int *v, int n) {
	my_qsort_impl(v, 0, n);
}

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

	int n;
    scanf("%d", &n);
    assert(n > 0);

    int *v = (int*)malloc(n * sizeof(int));
    for (int i = 0; i < n; i++) {
    	scanf("%d", &v[i]);
    }

    my_qsort(v, n);

    for (int i = 0; i < n; i++) {
		printf("%d ", v[i]);
	}

    return 0;
}