二分查找的必要条件是必须有序的数列 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)); }
打印结果:
以上是java如何使用二分查找数组中指定元素的详细内容。更多信息请关注PHP中文网其他相关文章!