Cod sursa(job #1339892)

Utilizator BonCipBonciocat Ciprian Mircea BonCip Data 11 februarie 2015 11:58:22
Problema Sortare prin comparare Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2.11 kb
#include <algorithm>
#include <stdio.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);
            if (l < r) {
                aux = v[l];
                v[l] = v[r];
                v[r] = aux;
            }
        }
        qsort(b, l);
        qsort(l, e);
    } else if (e - b == 4) {
        if (v[b + 1] < v[b]) {
            aux = v[b + 1];
            v[b + 1] = v[b];
            v[b] = aux;
        }
        if (v[b + 2] < v[b]) {
            aux = v[b + 2];
            v[b + 2] = v[b];
            v[b] = aux;
        }
        if (v[b + 3] < v[b]) {
            aux = v[b + 3];
            v[b + 3] = v[b];
            v[b] = aux;
        }
        if (v[b + 2] < v[b + 1]) {
            aux = v[b + 2];
            v[b + 2] = v[b + 1];
            v[b + 1] = aux;
        }
        if (v[b + 3] < v[b + 1]) {
            aux = v[b + 3];
            v[b + 3] = v[b + 1];
            v[b + 1] = aux;
        }
        if (v[b + 3] < v[b + 2]) {
            aux = v[b + 2];
            v[b + 3] = v[b + 2];
            v[b + 2] = aux;
        }
    } else if (e - b == 3) {
        if (v[b + 1] < v[b]) {
            aux = v[b + 1];
            v[b + 1] = v[b];
            v[b] = aux;
        }
        if (v[b + 2] < v[b]) {
            aux = v[b + 2];
            v[b + 2] = v[b];
            v[b] = aux;
        }
        if (v[b + 2] < v[b + 1]) {
            aux = v[b + 2];
            v[b + 2] = v[b + 1];
            v[b + 1] = 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]);
    }
}