Pagini recente » Cod sursa (job #1285951) | Cod sursa (job #1177764) | Cod sursa (job #257898) | Cod sursa (job #2124648) | Cod sursa (job #2279637)
#include <ctime>
#include <cstdlib>
#include <fstream>
#define VMAX 3000010
std::ifstream fin("sdo.in");
std::ofstream fout("sdo.out");
int n, k;
unsigned int v[VMAX];
int partition(int lo, int hi) {
int rnd = rand() % (hi - lo + 1) + lo;
unsigned int aux = v[rnd];
v[rnd] = v[hi];
v[hi] = aux;
unsigned int p = v[lo];
int l = lo, r = hi;
while (l < r) {
while (l < r && v[r] >= p)
r--;
v[l] = v[r];
while (l < r && v[l] <= p)
l++;
v[r] = v[l];
}
v[r] = p;
return r;
}
unsigned int quick(int lo, int hi) {
int pivot = partition(lo, hi);
if (pivot == k)
return v[k];
if (k < pivot) {
if (pivot - 1 > lo)
return quick(lo, pivot - 1);
return v[k];
}
if (pivot + 1 < hi)
return quick(pivot + 1, hi);
return v[k];
}
int main() {
int i;
srand(time(NULL));
fin >> n >> k;
for (i = 1; i <= n; i++)
fin >> v[i];
fout << quick(1, n) << '\n';
fout.close();
return 0;
}