Cod sursa(job #1807934)

Utilizator fluture.godlikeGafton Mihnea Alexandru fluture.godlike Data 17 noiembrie 2016 08:48:41
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.99 kb
#include <cstdio>
#include <algorithm>
#include <cstdlib>

#define in "algsort.in"
#define out "algsort.out"
#define NMAX (500000 + 7)
#define RANDVAL 163
#define Konst 34

using namespace std;
int n, v[NMAX];

int random(const int &St, const int &Dr)
{
    return St + (1LL*rand()*rand() + Konst)%(Dr-St+1);
}

void qSort(const int &st, const int &dr)
{
    if(st >= dr) return ;
    int pivot = v[random(st, dr)], x = st, y = dr;
    while(x <= y)
    {
        for( ; (v[x] < pivot) && x<= dr; ++x);
        for( ; (v[y] > pivot) && y>= st; --y);
        if(x <= y)
        {
            swap(v[x], v[y]);
            ++x;
            --y;
        }
    }
    qSort(st, y);
    qSort(x, dr);
}

int main()
{
    freopen(in, "r", stdin);
    freopen(out, "w", stdout);
    srand(RANDVAL);
    scanf("%d", &n);
    for(int i = 1; i<= n; ++i) scanf("%d", &v[i]);
    qSort(1, n);
    for(int i = 1; i<= n; ++i) printf("%d ", v[i]);
    printf("\n");
    return 0;
}