Cod sursa(job #1340100)

Utilizator BonCipBonciocat Ciprian Mircea BonCip Data 11 februarie 2015 15:27:43
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.09 kb
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#define MAX 500000
using namespace std;
 
int v[MAX];
 
void qsort(int b, int e)
{
    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;
        qsort(b, l);
        qsort(l, e);
    } 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);
    }
    qsort(0, N);
    //sort(v, v + N);
    for (i = 0; i < N; i++) {
        printf("%d ", v[i]);
    }
}