Pagini recente » Cod sursa (job #2987063) | Cod sursa (job #598462) | Cod sursa (job #1163902) | Cod sursa (job #1205215) | Cod sursa (job #2618424)
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
ifstream f("sdo.in");
ofstream g("sdo.out");
int v[100001];
int normal_partition(int left,int right)
{
int pivot,poz,i;
poz = left;
pivot = right;
for(i=left; i<right; i++)
{
if(v[i] < v[pivot])
{
swap(v[i],v[poz]);
poz++;
}
}
swap(v[pivot],v[poz]);
return poz;
}
int random_partition(int left,int right)
{
int temp;
if(right-left+1)
{
temp = left + rand() % (right - left + 1);
}
swap(v[right],v[temp]);
return normal_partition(left,right);
}
int quickSelect(int left,int right,int k)
{
int aux,temp;
if(left==right)
{
return v[left];
}
aux = random_partition(left,right);
temp = aux - left + 1;
if(k <= temp)
{
return quickSelect(left,aux,k);
}
else
{
return quickSelect(aux + 1,right,k - temp);
}
}
int main()
{
int n,i,k;
f>>n>>k;
for(i=0; i<n; i++)
{
f>>v[i];
}
g<<quickSelect(0,n-1,k);
return 0;
}