二分法bug修复

public class Main {

    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6,7,8,9,10};
        int a = 7;
        int result = Main.query(arr,a);
        System.out.println(result);
    }

    private static int query(int[] arr , int goal){
        int index = -1;
        int low = 0;
        int high = arr.length-1;
        while (low <= high){
            index = (low+high)/2;
            if(arr[index] < goal){
                low = index +1;
            }else if(arr[index] > goal){
                high = index - 1;
            }else if(arr[index] == goal){
                return index;
            }
        }
        return -1;

    }
}

以上代码是基本的二分法查找给出数据所在位置的最基本方法,但是在里面存在一个bug,int+int到底是不是符合我们生活中的实际,1+1确实等于2,但是2147483647+2147483647等于4294967294吗?错!

经检验,2147483647+2147483647等于-2.所以当一个数组特别长时,它的两个数组下标相加超出int类型的最大值时,就不符合我们的实际了,所以改为>>>无符号右移,相当于实际中的除以2.经验证,可以完美的解决这个bug,及

index = (low+high)/2;改为index = (low+high)>>>1。
posted @ 2017-09-07 14:38  忆殇314  阅读(263)  评论(0编辑  收藏  举报