Cod sursa(job #966156)

Utilizator Theorytheo .c Theory Data 25 iunie 2013 14:03:19
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
//quicksort with random choice of the pivot

#include<fstream>
#include<cstdlib>
#include<ctime>

using namespace std;


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


const int Nmax = 500009;

int N; int K; int A[Nmax];


void Read(){

    fin >> N;

    for(int i = 1; i <= N; ++i) fin >> A[i];
}


int Partition(int Left, int Right){

    int Lt = Left - 1; int Rt = Right + 1; int Pivot = A[Left + rand() % (Right - Left + 1)];
    while(1){

        do{
            ++Lt;
        }while(A[Lt] < Pivot);


        do{
            --Rt;
        }while(Pivot < A[Rt]);


        if(Lt < Rt)
            swap(A[Lt], A[Rt]);
       else return Lt;
    }
    return 0;
}

void Quicksort(int Left, int Right){

    if(Right == Left)   return;

    int q = Partition(Left, Right);

    if(q < Right)
        Quicksort(q , Right);

    if(Left < q - 1)
        Quicksort(Left, q - 1);
}


void Print(){

    for(int i = 1; i <= N; ++i)
        fout << A[i] <<" ";
}


int main(){

    srand(time(NULL));

    Read ();
    Quicksort(1, N);

    Print();
    return 0;
}