Cod sursa(job #1538896)

Utilizator RathebaSerbanescu Andrei Victor Ratheba Data 29 noiembrie 2015 23:06:22
Problema Sortare prin comparare Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <cstdio>
#include <cstdlib>
#include <ctime>

using namespace std;

const int MAX = 100003;

void qSort(int first, int last);

int v[MAX], n;

int main()
{
    freopen("algsort.in", "r", stdin);
    freopen("algsort.out", "w", stdout);

    srand (time(NULL));

    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]);
    return 0;
}
void qSort(int first, int last)
{

    int i, j, aux, pivot;
    i = first - 1;
    j = last + 1;
    pivot = v[first + rand() % (last - first)];
    while(1)
    {
        do{ j--; } while(v[j] > pivot);
        do{ i++; } while(v[i] < pivot);

        if(i < j)
        {
            aux = v[i];
            v[i] = v[j];
            v[j] = aux;
        }
        else
            break;
    }
    if(first < j)
        qSort(first, j);
    if(j+1 < last)
        qSort(j+1, last);
}