Pagini recente » Cod sursa (job #2293181) | Cod sursa (job #1328386) | Cod sursa (job #817417) | Cod sursa (job #1280888) | Cod sursa (job #2538087)
#include <cstdio>
#include <iostream>
#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 + to) / 2;
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);
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> N >> K;
for (int i = 1; i <= N; i++) {
cin >> nums[i];
}
cout << getKthElem(1, N, K) << "\n";
return 0;
}