/*
* 面试题40:最小的k个数
* 题目:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
* 思路:冒泡排序
*/
import java.util.ArrayList;
public class No40GetLeastNumbers_Solution {
public static void main(String[] args) {
No40GetLeastNumbers_Solution n = new No40GetLeastNumbers_Solution();
int [] array = {2, 5, 7, 8, 4, 2, 7, 9};
ArrayList<Integer> list = n.GetLeastNumbers_Solution(array, 4);
if (list != null) {
for (int i = 0; i < list.size();i++) {
System.out.println(list.get(i));
}
}else {
System.out.println(" ");
}
}
public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
ArrayList< Integer> list = new ArrayList<Integer>();
if (input == null || input.length == 0 || k <= 0 || k > input.length ) {
return list;
}
for (int i = 0; i < k; i++) {
for(int j = 0; j < input.length - i - 1; j++) {
if (input[j] < input[j + 1]) {
int temp = input[j];
input[j] = input[j + 1];
input[j + 1] = temp;
}
}
list.add(input[input.length - i -1]);
}
return list;
}
}