package class01; import java.util.Arrays; /** * 在arr上,返回arr中大于等于targetNum的最左的位置。 * (如果有,就返回这个最左的索引。如果没有,可以返回-1。) * 使用了二分法。 */ public class Code05_BSNearLeft { public static void main(String[] args) { int maxSize = 30; int maxValue = 50; int testTimes = 10000; boolean flag = true; for (int i = 0; i < testTimes; i++) { int[] arr = generateRandomArr(maxSize, maxValue); int[] arr2 = copyArr(arr); Arrays.sort(arr); int targetNum = (int) (Math.random() * maxValue); int resultNum = nearestIndex(arr, targetNum); int test = test(arr, targetNum); if (resultNum != test) { System.out.println("oops!"); flag = isFlag(arr, arr2, targetNum, resultNum, test); } } //及时所有的测试都通过了,也打印一次数据,查看结果。 int[] arr = generateRandomArr(maxSize, maxValue); int[] arr2 = copyArr(arr); Arrays.sort(arr); int targetNum = (int) (Math.random() * maxValue); int test = test(arr, targetNum); int resultNum = nearestIndex(arr, targetNum); isFlag(arr, arr2, targetNum, resultNum, test);//方法复用 System.out.println(flag ? "nice!" : "oops!"); } private static boolean isFlag(int[] arr, int[] arr2, int targetNum, int resultNum, int test) { System.out.println("================================================"); boolean flag; flag = false; System.out.println("原数组:"); printArr(arr2);//原数组 System.out.println("升序数组:"); printArr(arr);//升序数组 for (int index = 0; index < arr.length; index++) {//打印索引,看着方便。 System.out.print(index + "\t"); } System.out.println(); System.out.println("targetNum = " + targetNum); System.out.println("test = " + test); System.out.println("resultNum = " + resultNum); System.out.println("================================================"); return flag; } //核心方法 public static int nearestIndex(int[] arr, int num) { int L = 0; int R = arr.length - 1; int temp = -1; while (L <= R) { int mid = L + ((R - L) >> 1); if (arr[mid] >= num) { temp = mid; R = mid - 1; } else { L = mid + 1; } } return temp; } public static int[] generateRandomArr(int maxSize, int maxValue) { int[] arr = new int[(int) (Math.random() * maxSize)]; for (int i = 0; i < arr.length; i++) { arr[i] = (int) (Math.random() * maxValue) - (int) (Math.random() * maxValue); } return arr; } public static void printArr(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + "\t"); } System.out.println(); } public static int test(int[] arr, int targetNum) { for (int i = 0; i < arr.length; i++) { if (arr[i] >= targetNum) { return i; } } return -1; } public static int[] copyArr(int[] arr1) { int[] arr2 = new int[arr1.length]; for (int i = 0; i < arr1.length; i++) { arr2[i] = arr1[i]; } return arr2; } }
标签:arr,targetNum,int,System,test,大于,out From: https://www.cnblogs.com/TheFloorIsNotTooHot/p/16838647.html