Pagini recente » Cod sursa (job #2523727) | Cod sursa (job #1831948) | Cod sursa (job #1112776) | Cod sursa (job #2624678) | Cod sursa (job #2624351)
#include <fstream>
#include <stdlib.h>
using namespace std;
#define maxn 3000001
int n, k, i, j, ind_pivot;
long long int v[maxn], pivot;
void swap(long long int *x, long long int *y){
int temp = *x;
*x = *y;
*y = temp;
}
long long int partition(int l, int r){
pivot = v[l + (rand() % (r - l))];
i = l; j = r;
while(i <= j) {
while(v[i] < pivot)
i++;
while(v[j] > pivot)
j--;
if(i <= j) {
swap(&v[i], &v[j]);
i++;
j--;
}
}
return i;
}
long long int quickSelect(int st, int dr, int index){
ind_pivot = partition(st, dr);
if(ind_pivot - st == index-1)
return v[ind_pivot];
if(ind_pivot - st > index-1)
return quickSelect(st, ind_pivot - 1, index);
return quickSelect(ind_pivot + 1, dr, index - ind_pivot + st - 1);
}
int main() {
ifstream f("sdo.in");
ofstream g("sdo.out");
f >> n >> k;
for(i = 0; i < n; i++)
f >> v[i];
quickSelect(0, n-1, k);
g << v[k];
return 0;
}