Cod sursa(job #1744324)

Utilizator whoasdas dasdas who Data 19 august 2016 16:53:30
Problema Sortare prin comparare Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.89 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;


void my_insertion_sort(int *v, int l, int r) {
	for (int i = l; i < r; i++) {
		int j, x = v[i];
		for (j = i - 1; j >= l && v[j] > x; j--) {
			v[j + 1] = v[j];
		}
		v[j + 1] = x;
	}
}

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

/** Partitions v as such: [ < )[ >= )
 * This is so that we don't need to move/swap elements that are equal to the pivot
 * @return the index of the common boundary (lt_hi == ge_lo) */
int partition(int *v, int l, int r, int pivot) {
	int boundary = l;
	for (int i = l; i < r; i++) {
		if (v[i] < pivot) {
			swap(v[i], v[boundary]);
			boundary++;
		}
	}
	return boundary;
}

void my_qsort_impl(int *v, int l, int r, int threshold) {
	int n = r - l;
	if (n <= 1) {
		return;
	} else if (n <= threshold) {
		my_insertion_sort(v, l, r);
		return;
	}
	swap(v[r - 1], v[rand_int(l, r)]); // select random pivot and bring it to the last position
	int boundary = partition(v, l, r - 1, v[r - 1]); // partition
	swap(v[r - 1], v[boundary]); // bring pivot to its final position
	my_qsort_impl(v, l, boundary, threshold); // don't include the pivot (otherwise we'd risk entering an infinite loop)
	my_qsort_impl(v, boundary + 1, r, threshold); // again, don't include the pivot
}


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

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;
}