#include <cstdlib>
#include <cstdio>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
void qfind(vector<int>& a, int k, int left, int right, vector<int>&res ) {
if (left > right || k <= 0) return;
if (right - left + 1 <= k) {
while (left <= right) res.push_back(a[left++]);
return;
}
int pivot = a[left];
int i = left, j = right;
while (i < j) {
while (i < j && a[j] > pivot) j--;
if (i < j) a[i++] = a[j];
while (i < j && a[i] <= pivot) i++;
if (i < j) a[j--] = a[i];
}
a[i] = pivot;
qfind(a, k, left, i - 1 , res);
if (k - (i-1-left + 1) > 0) res.push_back(a[i]);
qfind(a, k-(i-left+1), i + 1, right, res);
}
vector<int> findKth(vector<int>& a, int k) {
std::vector<int> res;
qfind(a, k, 0, a.size() - 1, res);
return res;
}
vector<int> findKth_heap(vector<int>& a, int k) {
if (a.size() <= k) return a;
vector<int> h(a.begin(), a.begin()+k);
//auto cmp = (const int x, const int y){return x < y;};
// max heap
make_heap(h.begin(), h.end());
for (int i = k; i < a.size(); i++) {
if (a[i] < h[0]) {
pop_heap(h.begin(), h.end());
h[k-1] = a[i];
push_heap(h.begin(), h.end());
}
}
return h;
}
void p(const vector<int>& a) {
for (auto i = a.begin(); i != a.end(); i++) printf("%d ", *i);
printf("\n");
}
int main() {
int a[] = {-1,1,1,1,1,1,1,1,11};
//int a[] = {9,8,7,6,45,5,4,3,4,2,1,1};
//int a[] = {1, 2,3,4 ,5 ,6, 7 ,8};
vector<int> v(a, a + sizeof(a) / sizeof(int));
auto res = findKth(v, 5);
auto res2 = findKth_heap(v, 5);
sort(res.begin(), res.end());
sort(res2.begin(), res2.end());
p(res);
p(res2);
return 0;
}