AcWing 786. 第k个数
原题链接
简单
作者:
haah
,
2020-12-06 10:23:02
,
所有人可见
,
阅读 329
JAVA代码
import java.io.*;
/**
* @Author: ChangAo
* @Date: 2020/12/6 9:17
*/
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String[] s = br.readLine().split(" ");
int num = Integer.parseInt(s[0]);
int a = Integer.parseInt(s[1]);
String[] res = br.readLine().split(" ");
int[] arr = new int[num];
for (int i=0; i < num; i++)
arr[i] = Integer.parseInt(res[i].trim());
quicksort(arr, 0, num-1);
bw.write(String.valueOf(arr[a-1]));
bw.flush();
}
public static void quicksort(int[] arr, int l, int r){
// 递归终止条件
if (l >= r)
return;
// 分界点
int x = arr[l + r >> 1];
// 设置两个指针
int i = l-1;
int j = r+1;
while (i < j){
do i++;while (arr[i] < x);
do j--;while (arr[j] > x);
if (i < j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
quicksort(arr, l, j);
quicksort(arr, j+1, r);
}
}