package com.xgk.chapterone;
import java.util.Scanner;
public class FindK {
@SuppressWarnings(“all”)
public static void main(String[] args) {
int[] arr = { 48, 36, 61, 82, 72, 11, 58, 48 };
Scanner sc = new Scanner(System.in);
int k = 0;
System.out.println(“Enter the K:”);
try {
k = sc.nextInt();
} catch (Exception e) {
System.out.println(“You had entered a wrong number!”);
System.exit(0);
}
// 方法一:对数组进行冒泡倒向排序,取出第K个值
System.out.println(method_one(arr)[k - 1]);
// 方法二:定义一个长度为K的数组,将原数组的前K个元素取出放入数组,冒泡倒序排序数组,
// 将原数组的剩余元素与数组第K个值比较做初步判断,如果小于直接舍弃,如果大
// 于进行插入,将后边元素向后移一位,并将数组第K个元素挤出数组
System.out.println(method_two(arr, k)[k - 1]);
}
private static int[] method_two(int[] arr, int k) {
int[] arr1 = new int[k];
// 写入时即进行插入排序
for (int i = 0; i < arr.length; i++) {
if (arr[i] > arr1[arr1.length - 1]) {
for (int j = 0; j < arr1.length; j++) {
if (arr[i] > arr1[j]) {
for (int j2 = arr1.length - 1; j2 < j; j2--) {
arr1[j2] = arr1[j2 - 1];
}
arr1[j] = arr[i];
break;
}
}
}
}
// 以下是成功的插入排序
// for (int i = 0; i < arr1.length; i++) {
// arr1[i]=arr[i];
// }
// int[] arr2 = method_one(arr1);
// for (int i = arr2.length; i < arr.length; i++) {
// if (arr[i] > arr2[arr2.length - 1]) {
// for (int j = 0; j < arr2.length; j++) {
// if (arr[i] > arr2[j]) {
// for (int j2 = arr2.length - 1; j2 < j; j2–) {
// arr2[j2] = arr2[j2 - 1];
// }
// arr2[j] = arr[i];
// // 着重注意!
// break;
// }
// }
// }
// }
return arr1;
}
private static int[] method_one(int[] arr) {
int temp = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = i; j < arr.length; j++) {
if (arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
}