利用快速排序的思想,找到中枢值为k,k之前的都比它小,k之后的都比它大:
java实现
public static int partition(int[] arr, int low, int high) {
int pivotValue = arr[low];
while (low < high) {
while (low < high && arr[high] >= pivotValue)
high--;
arr[low] = arr[high];
while (low < high && arr[low] <= pivotValue)
low++;
arr[high] = arr[low];
}
arr[low] = pivotValue;
return low;
}
public static void getLeastNumbers(int[] arr, int k) {
int low =0;
int high = arr.length-1;
int pivotKey = partition(arr, low, high);
while (pivotKey != k) {
System.out.println("pivotKey: " + pivotKey);
if (k < pivotKey) {
high = pivotKey - 1;
pivotKey = partition(arr, low, high);
}
else {
low = pivotKey+1;
pivotKey = partition(arr, low, high);
}
}
}