注意
二分查找要求原数组为有序序列,从小到大
递归解法
public class problem9 {public static void main(String[] args) {int[] arr = {1,2,3,4,6,7};int left = 0;int right = arr.length - 1;int value = 2;System.out.println(Arrays.toString(arr));int index = binary(arr, left, right, value);System.out.println(index);}
//递归解法public static int binary(int[] arr, int left, int right, int value) {if (left > right)
//没有找到就返回-1return -1;
//中间数的下标
/*1.(left+right)/2
* 2.(left + right) >>> 1:无符号右移1,相当于除以2
* */int midIndex=(left + right) >>> 1;
//中间数int middle = arr[midIndex];if (value > middle)
//如果比中间数大,就从中间数的右边进行查找return binary(arr, middle + 1, right, value);else if (value < middle)
//如果比中间数小,就从中间数的左边进行查找return binary(arr, left, middle - 1, value);else
//等于中间数,直接返回下标return midIndex;}
}
非递归解法
public class problem9_1 {public static void main(String[] args) {int[] arr = {1,2,3,4,6,7};int left = 0;int right = arr.length - 1;int value = 2;System.out.println(Arrays.toString(arr));int index = binary(arr, left, right, value);System.out.println(index);}//非递归解法public static int binary(int[] arr, int left, int right, int value) {while (left<=right){int midIndex=(left+right)>>>1;int middle=arr[midIndex];if (value>middle)left=midIndex+1;else if (value<middle)right=midIndex-1;elsereturn midIndex;}return -1;}}