Pagini recente » Cod sursa (job #3235782) | Cod sursa (job #570458) | Cod sursa (job #2381795) | Cod sursa (job #2976177) | Cod sursa (job #978934)
Cod sursa(job #978934)
#include<cstdio>
#include<cstdlib>
#include<fstream>
#define NMAX 3000005
int A[NMAX], n, k, pivot;
using namespace std;
int RandomizedPartition(int A[NMAX], int limInf, int limSup)
{
int RandNR = A[limInf + rand()%(limSup- limInf+1)] ;
int i = limInf -1 ;
int j = limSup + 1 ;
while (true )
{
do
{
++i;
}
while(A[i]< RandNR);
do
{
--j;
}
while(A[j]> RandNR);
if(i < j ) swap(A[i], A[j]);
else return j;
}
return 0;
}
void RandomizedSelect(int A[NMAX],int limInf, int limSup,int k)
{
if(limInf == limSup) return;
int q = RandomizedPartition(A,limInf,limSup) ;
int i = q - limInf + 1;
if( k <= i ) RandomizedSelect(A, limInf, q , k );
else RandomizedSelect(A, q + 1 , limSup, k-i );
}
void citire()
{
scanf("%d %d",&n,&k);
for(int i=1; i<=n; ++i)
{
scanf("%d",&A[i]);
}
}
int main()
{
freopen("sdo.in","r",stdin);
freopen("sdo.out","w",stdout);
citire();
RandomizedSelect(A,1,n,k);
printf("%d\n",A[k]);
return 0 ;
}