import java.util.Scanner;
public class GetLestNumbers {
// 判断数组是否为空
public static boolean checkInvalidArray(int[] numbers) {
if (numbers == null || numbers.length == 0)
return true;
return false;
}
// 基于快速排序算法的partition函数
public static int partition(int[] numbers, int left, int right) {
int result = numbers[left];
if (left > right) {
return -1;
}
while (left < right) {
while (left < right && numbers[right] >= result) {
right--;
}
numbers[left] = numbers[right];
while (left < right && numbers[left] < result) {
left++;
}
numbers[right] = numbers[left];
}
numbers[left] = result;
return left;
}
// 基于Partition函数的O(n)算法
public static int[] getLestNumbersK(int[] numbers, int k) {
int[] results = new int[k];
if (checkInvalidArray(numbers))
return null;
int length = numbers.length;
int start = 0;
int end = length - 1;
int index = partition(numbers, start, end);
while (index != k - 1) {
if (index > k - 1) {
end = index - 1;
index = partition(numbers, start, end);
} else {
start = index + 1;
index = partition(numbers, start, end);
}
}
for (int i = 0; i < k; i++) {
results[i] = numbers[i];
}
return results;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String string = input.nextLine();
int k = input.nextInt();
String[] inputnum = string.split(" ");
int[] numbers = new int[inputnum.length];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Integer.parseInt(inputnum[i]);
}
for (int number : getLestNumbersK(numbers, k)) {
System.out.print(number + " ");
}
}
}
网友评论