[Java] 纯文本查看 复制代码 public static void main(String[] args) {
int[] arr = {1, 3, 5, 9, 18, 27, 36, 88, 96, 102};
System.out.println("二分查找法的返回元素值是:"+getSearch(arr,96));
}
public static int getSearch(int[] arr, int num) {
int min = 0;
int max = arr.length - 1;
while (true) {
int mid = (max + min) / 2;
if (num > arr[mid]) {
min = mid + 1;
System.out.println("min运行了"+min);
} else if (num < arr[mid]) {
max = mid - 1;
System.out.println("max运行了"+max);
} else {
System.out.println("mid运行了");
return mid;
}
if(max < min) {
System.out.println("-1运行了");
return -1;
}
}
}
把mid的赋值放到循环里面就行了 |