思想:
首先使用快速排序
判断第K个数字在快速排序递归中处于分界点的左侧还是右侧。从所在侧继续进行递归
package cn.liyi.day01;
import java.util.Scanner;
/*
找到第K小的数字
* */
public class Demo786 {
public static int[] num = {1, 3, 5, 8, 2};
public static void main(String[] args) {
int k;
Scanner sc = new Scanner(System.in);
k = sc.nextInt();
for (int i = 0; i < 5; i++) {
System.out.print(num[i]);
}
System.out.println();
System.out.println(quickSort(0, 4, k));
}
public static int quickSort(int l, int r, int k) {
if (l == r)
return num[l];
int x = num[l], i = l - 1, j = r + 1;
while (i < j) {
do {
i++;
} while (num[i] < x);
do {
j--;
} while (num[j] > x);
if (i < j) {
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
int sl = j - l + 1;
if (k < sl)
return quickSort(l, j, k);
return quickSort(j + 1, r, k - sl);
}
}