import java.util.ArrayList;
/**
* 最小的K个数
*
* 输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。
*/
public class JZ029GetLeastNumbers {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> list = new ArrayList<>();
if (k <= 0 || k > input.length) {
return list;
}
int low = 0;
int high = input.length - 1;
quickSort(input, low, high);
for (int i = 0; i < k; i++) {
list.add(input[i]);
}
return list;
}
public void quickSort(int[] a, int low, int high) {
if (low < high) {
int index = getIndex(a, low, high);
quickSort(a, low, index - 1);
quickSort(a, index + 1, high);
}
}
public int getIndex(int[] a, int low, int high) {
int tmp = a[low];
while(low < high) {
while(low < high && a[high] > tmp) {
high--;
}
a[low] = a[high];
while(low < high && a[low] <= tmp) {
low++;
}
a[high] = a[low];
}
a[low] = tmp;
return low;
}
}