Pagini recente » Cod sursa (job #2656131) | Cod sursa (job #3164086) | Cod sursa (job #521100) | Cod sursa (job #3161003) | Cod sursa (job #526496)
Cod sursa(job #526496)
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
using namespace std;
#define NMAX 3000000
int vect[NMAX];
int partition_rand(int p, int r)
{
int rand_pos = p+(rand() % (r-p+1));
swap(vect[p],vect[rand_pos]);
int pivot = vect[p], left=p, right=r;
while (left < right)
{
while (vect[left] <= pivot && left != r) left++;
while (vect[right] > pivot) right--;
if (left < right)
{
swap(vect[left],vect[right]);
left++;
right--;
}
}
swap(vect[p],vect[right]);
return right;
}
int order_statistic(int p, int r, int searchKey)
{
if (p==r)
{
return vect[p];
}
int q = partition_rand(p,r);
int k = q-p+1;
if (k == searchKey)
{
return vect[q];
}
else if (k > searchKey)
{
return order_statistic(p,q-1,searchKey);
}
else return order_statistic(q+1,r,searchKey-k);
}
int main(void)
{
int n, searchKey;
srand((unsigned int)time(0));
freopen("sdo.in","r",stdin);
freopen("sdo.out","w",stdout);
scanf("%d %d",&n, &searchKey);
for (int i=0;i<n;i++)
scanf("%d",&vect[i]);
printf("%d\n",order_statistic(0,n-1,searchKey));
return 0;
}