Cod sursa(job #966145)

Utilizator Theorytheo .c Theory Data 25 iunie 2013 13:50:18
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
//quicksort with random choice of the pivot

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

using namespace std;


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


const int Nmax = 3000009;

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


void Read(){

    fin >> N >> K;

    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 - 1);
    }
    return 0;
}

void Quicksort(int Left, int Right, int K){

    if(Right == Left)   return;

    int q = Partition(Left, Right);
    int t = q - Left + 1;

    if(t < K)
        Quicksort(q + 1, Right, K - t);
    else Quicksort(Left, q, K);
}


void Print(){

    fout << A[K] <<'\n';
}


int main(){

    srand(time(NULL));

    Read ();
    Quicksort(1, N, K);

    Print();
    return 0;
}