二分查找(java)

1.注意对输入参数的正确性判断
2. int middle = left + ((right - left) >> 1),有效防止越界

public class BinarySearch {
    public int binary_search(int array[],int len  , int value)
    {
        if(array==null||array.length==0)
            return -1;
        int left = 0;
        int right = len - 1;
        while(left <= right){
            int middle = left + ((right - left) >> 1);

            if(array[middle] > value){
                right = middle - 1;
            }
            else if(array[middle] < value){
                left = middle + 1;
            }
            else
                return middle;

        }
        return -1;
    }
    public static void main(String[] args) {
        int array[]={1,2,3,4,7,8,9};
        BinarySearch bs=new BinarySearch();
        int result=bs.binary_search( array , array.length , 9);
        System.out.println("result:"+result);
    }
}

posted on 2016-04-24 23:31  决心1119  阅读(124)  评论(0编辑  收藏  举报

导航