二分查找的必要条件是必须有序的数列 public static int binarySearch(int[] array,int key){ int left = 0; int right = array.length-1; while(left <= right){ int mid = (left+right)/2; if(array[mid] > key){ right = mid - 1; }else if(array[mid] < key){ left = left + 1; }else{ return mid; } } return -1; } public static void main(String[] args) { int[] array = {12,14,15,16,18,23}; System.out.println(binarySearch(array, 15)); }
Print result:
The above is the detailed content of How to use binary search to specify elements in an array in java. For more information, please follow other related articles on the PHP Chinese website!