Cod sursa(job #1340109)

Utilizator BonCipBonciocat Ciprian Mircea BonCip Data 11 februarie 2015 15:37:47
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.13 kb
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#define MAX 500000
using namespace std;
 
int v[MAX];
int b, e;

void qsort()
{
    int aux;
    if (e - b > 4) {
        int piv = v[(b + e) / 2];
        int l = b - 1, r = e;
        while (l < r) {
            while (v[++l] < piv);
            while (v[--r] > piv);
            aux = v[l];
            v[l] = v[r];
            v[r] = aux;
        }
		aux = v[l];
		v[l] = v[r];
		v[r] = aux;
		
		aux = e;
		e = l;
        qsort();
		e = aux;
		aux = b;
		b = l;
        qsort();
		b = aux;
    } else if (e - b == 4) {
        int b1 = b + 1, b2 = b + 2, b3 = b + 3;
        if (v[b1] < v[b]) {
            aux = v[b1];
            v[b1] = v[b];
            v[b] = aux;
        }
        if (v[b2] < v[b]) {
            aux = v[b2];
            v[b2] = v[b];
            v[b] = aux;
        }
        if (v[b3] < v[b]) {
            aux = v[b3];
            v[b3] = v[b];
            v[b] = aux;
        }
        if (v[b2] < v[b1]) {
            aux = v[b2];
            v[b2] = v[b1];
            v[b1] = aux;
        }
        if (v[b3] < v[b1]) {
            aux = v[b3];
            v[b3] = v[b1];
            v[b1] = aux;
        }
        if (v[b3] < v[b2]) {
            aux = v[b3];
            v[b3] = v[b2];
            v[b2] = aux;
        }
    } else if (e - b == 3) {
        int b1 = b + 1, b2 = b + 2;
        if (v[b1] < v[b]) {
            aux = v[b1];
            v[b1] = v[b];
            v[b] = aux;
        }
        if (v[b2] < v[b]) {
            aux = v[b2];
            v[b2] = v[b];
            v[b] = aux;
        }
        if (v[b2] < v[b1]) {
            aux = v[b2];
            v[b2] = v[b1];
            v[b1] = aux;
        }
    } else if (e - b == 2) {
        if (v[b + 1] < v[b]) {
            aux = v[b + 1];
            v[b + 1] = v[b];
            v[b] = aux;
        }
    }
}
 
int main()
{
    freopen("algsort.in", "r", stdin);
    freopen("algsort.out", "w", stdout);
    int N;
    scanf("%d", &N);
    int i;
    for (i = 0; i < N; i++) {
        scanf("%d", v + i);
    }
	b = 0, e = N;
    qsort();
    for (i = 0; i < N; i++) {
        printf("%d ", v[i]);
    }
}