public class Search { public static void main(String[] args) { int[] arr = {12,16,30,45,63,79}; int index = binarySearch(arr, 16); System.out.println(index); } public static int binarySearch(int[] arr, int target) { int low = 0; int high = arr.length - 1; // 注意判断条件,必须是 <= while(low <= high){ // mid防止越界 int mid = low + (high - low) / 2; if(arr[mid] > target){ high = mid - 1; } else if(arr[mid] < target){ low = mid + 1; } else{ return mid; } } return -1; } }
原文:https://www.cnblogs.com/holdyoung/p/14840533.html