Cod sursa(job #283029)

Utilizator silvia_the_bestSilvia Pripoae silvia_the_best Data 18 martie 2009 17:24:32
Problema Sortare prin comparare Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include <cstdio>
#include <cstdlib>
#include <ctime>
#define N 500010
#define FIN "algsort.in"
#define FOUT "algsort.out"

int n, v[N];

void read()
{
    freopen(FIN, "r", stdin);

    scanf("%d", &n);

    for (int i = 1; i <= n; ++i)
        scanf("%d", &v[i]);
}

void swap(int &a, int &b)
{
    int c;
    c = a;
    a = b;
    b = c;
}

void quicksort(int x, int y)
{
    if (x >= y)
        return;
    int i = x - 1, j, p;
    p = rand() % (y - x + 1) + x;
    swap(v[p], v[y]);
    for (j = x; j <= y; ++j)
        if (v[j] <= v[y])
        {
            swap(v[++i], v[j]);
        }
    quicksort(x, i - 1);
    quicksort(i + 1, y);
}

void write()
{
    freopen(FOUT, "w", stdout);

    for (int i = 1; i < n; ++i)
        printf("%d ", v[i]);
    printf("%d\n", v[n]);
}

int main()
{
    srand(time(0));
    read();

    quicksort(1, n);

    write();
}