#include<iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 10010;
int arr[N];
int k, n;
int partition(int left, int right) {
int hh = left+1, tt = right;
int pivot = arr[left];
while (hh <= tt) {
while (arr[hh] < pivot&&hh <= right) hh++;
while (arr[tt] > pivot&&tt >= left) tt--;
if (hh < tt) {
swap(arr[hh], arr[tt]);
hh++; tt--;
}
}
swap(arr[left], arr[tt]);
return tt;
}
int f(int k) {
int count_left = 0;
int left = 1,right = n;
while (count_left != k) {
count_left = partition(left,right);
if (count_left < k) {
left = count_left + 1;
count_left = partition(count_left+1, right);
}
else {
right = count_left - 1;
count_left = partition(left, count_left - 1);
}
}
return arr[count_left];
}
int main() {
cin >> n >> k;
for (int i = 1; i <= n; i++) {
cin >> arr[i];
}
printf("%d",f(k));
return 0;
}
/*
8 3
1 2 3 4 5 6 7 8
5 3
1 6 3 5 2
6 2
5 3 1 6 8 4
*/
快排之寻找第K小的数
最新推荐文章于 2022-06-04 16:03:30 发布