输入数组和k,返回第k小数。
input:
3 2 1 5 4 6 2
3
output:
3
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String[] arr = str.split(" ");
int[] a = new int[arr.length];
for (int j = 0; j < arr.length; j++) {
a[j] = Integer.parseInt(arr[j]);
}
int k = sc.nextInt();
System.out.println(solution(a, k, 0, a.length - 1));
}
public static int partition(int[] a, int low, int high) {//一次快排
int middle = a[low];
while (low < high) {
while (low < high && a[high] >= middle)
high--;
if (low < high)
a[low++] = a[high];
while (low < high && a[low] <= middle)
low++;
if (low < high)
a[high--] = a[low];
}
a[low] = middle;
return low;
}
public static int solution(int[] a, int k, int low, int high) {
int middleIndex = partition(a, low, high);//找出分段点
middleIndex = middleIndex - low;
if (k == middleIndex + 1) {
return a[middleIndex + low];
} else if (k < middleIndex + 1) {
return solution(a, k, low, middleIndex - 1 + low);
} else {
return solution(a, k - middleIndex - 1, middleIndex + 1 + low, high);
}
}
}