Pagini recente » Cod sursa (job #148716) | Cod sursa (job #2752408) | Cod sursa (job #2776560) | Cod sursa (job #3279259) | Cod sursa (job #2538082)
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <algorithm>
using namespace std;
const int NMAX = 3000505;
int N, K;
int nums[NMAX];
int getKthElem(int from, int to, int K) {
int pivotIdx = from + rand() % (to - from + 1);
int pivotValue = nums[pivotIdx];
int elemsLtePivot = 0;
for (int idx = from; idx <= to; idx++) {
if (nums[idx] <= pivotValue) {
elemsLtePivot++;
}
}
swap(nums[pivotIdx], nums[from + elemsLtePivot - 1]);
// pivot is on the right position now
int nextAvailablePosLeft = from;
for (int idx = from; idx <= to; idx++) {
if (idx == from + elemsLtePivot - 1) {
continue;
}
if (nums[idx] <= pivotValue) {
swap(nums[idx], nums[nextAvailablePosLeft]);
nextAvailablePosLeft++;
}
}
if (K == elemsLtePivot) {
return pivotValue;
}
return K > elemsLtePivot
? getKthElem(from + elemsLtePivot, to, K - elemsLtePivot)
: getKthElem(from, from + elemsLtePivot - 2, K);
}
int main() {
freopen("sdo.in", "r", stdin);
freopen("sdo.out", "w", stdout);
scanf("%d%d", &N, &K);
for (int i = 1; i <= N; i++) {
scanf("%d", &nums[i]);
}
srand(time(0));
printf("%d\n", getKthElem(1, N, K));
return 0;
}