Pagini recente » Cod sursa (job #2723624) | Cod sursa (job #2877616) | Cod sursa (job #2496921) | Cod sursa (job #2877854) | Cod sursa (job #1851743)
#include <fstream>
#include <ctime>
#include <cstdlib>
using namespace std;
#define MAX_N 3000005
ifstream fin("sdo.in");
ofstream fout("sdo.out");
int n, k;
int a[MAX_N];
int part(int a[], int l, int r) {
int i = l - 1;
int j = r + 1;
int p = a[l + (rand() % (r - l + 1))];
while (true) {
do {
i++;
} while (a[i] < p);
do {
j--;
} while (p < a[j]);
if (i < j) {
swap(a[i], a[j]);
} else {
return j;
}
}
return 0;
}
void nth_element(int a[], int l, int r, int k) {
if (l == r) {
return;
}
int p = part(a, l, r);
int length = p - l + 1;
if (length >= k) {
nth_element(a, l, p, k);
} else {
nth_element(a, p + 1, r, k - length);
}
}
int main() {
fin >> n >> k;
for (int i = 1; i <= n; i++) {
fin >> a[i];
}
srand(time(NULL));
nth_element(a, 1, n, k);
fout << a[k];
return 0;
}