Cod sursa(job #457865)

Utilizator DastasIonescu Vlad Dastas Data 21 mai 2010 20:02:59
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <algorithm>

using namespace std;

ifstream in("algsort.in");
ofstream out("algsort.out");

int Partitie(int A[], int st, int dr)
{
    int poz = st + (rand() % (dr - st + 1));
    swap(A[poz], A[st]);
    int V = A[st];

    --st; ++dr;
    while ( st < dr )
    {
        do
            --dr;
        while ( st < dr && A[dr] > V );

        do
            ++st;
        while ( st < dr && A[st] < V );

        if ( st < dr )
            swap(A[st], A[dr]);
    }

    return dr;
}

void Quicksort(int A[], int st, int dr)
{
    while ( st < dr )
    {
        int P = Partitie(A, st, dr);
        if ( P - st < dr - P - 1 )
        {
            Quicksort(A, st, P);
            st = P + 1;
        }
        else
        {
            Quicksort(A, P + 1, dr);
            dr = P;
        }
    }
}

int A[500020];
int main()
{
    int n;
    srand((unsigned)time(0));

    in >> n;
    for ( int i = 1; i <= n; ++i )
        in >> A[i];
    Quicksort(A, 1, n);

    for ( int i = 1; i <= n; ++i )
        out << A[i] << " ";

    return 0;
}