Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- int partition(std::vector<int>& v, int l, int r) {
- if (r - l <= 1) return l;
- std::swap(v[r - 1], v[(r + l) / 2]);
- int i = l;
- const int& x = v[r - 1];
- for (int j = l; j < r - 1; ++j) {
- if (v[j] < x) {
- std::swap(v[i], v[j]);
- ++i;
- }
- }
- std::swap(v[i], v[r - 1]);
- return i;
- }
- int KStat(std::vector<int>& v, int k) {
- int l = 0, r = v.size();
- while (true) {
- const int p = partition(v, l, r);
- if (p == k) return v[k];
- if (p > k) {
- r = p;
- } else {
- l = p + 1;
- }
- }
- }
- int main() {
- int n = 0, k = 0;
- std::cin >> n >> k;
- std::vector<int> v(n, 0);
- for (int i = 0; i < n; ++i) {
- std::cin >> v[i];
- }
- std::cout << KStat(v, k);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement