编写函数实现有序数组的二分查找

算法不用就忘,mark

    public static void binary_search(int target,int [] arr){
        if (arr== null || arr.length == 0){
            System.out.println("not find");
            return;
        }
        int bottom = 0;
        int top = arr.length-1;
        int mid = 0;

        while (true){
            mid = (bottom+top)/2;
            if (bottom > top) {
                //not find
                System.out.println("not find");
                return;
            }else if (target == arr[mid]){
                //find target
                System.out.println("find it at "+mid);
                return;
            }else if(target <arr[mid]){
                //在左半边
                top=mid-1;
            }else if(target >arr[mid]){
                //在右半边
                bottom = mid+1;
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/u011109881/article/details/79736436