Pagini recente » Cod sursa (job #2059881) | Cod sursa (job #1525650) | Cod sursa (job #1327414) | Cod sursa (job #2891830) | Cod sursa (job #966145)
Cod sursa(job #966145)
//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;
}