欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

二分查找的错误写法

程序员文章站 2022-03-02 12:15:12
...
public class W {

    public static void main(String[] args) {
        int[] a = {1,2,3,4,5,6,7,8,9};
        int b = midSearch(a,0,a.length-1,7);
        System.out.println(a[b]);
    }

    public static int midSearch(int a[],int start,int end,int target){

        while (start <= end){
            int mid = (start+end)/2;
            if(a[mid] == target){
                return mid;
            }else if(a[mid] < target){
                //第一次进来的时候 start=0 end=8
                //这里虽然递归调用了 但是里面返回的6 却给予了c 所以会继续递归死循环的执行
                int c = midSearch(a,mid+1,end,target);
                System.out.println(c);
            }else{
                midSearch(a,start,mid-1,target);
            }
        }
        return -1;
    }
}

打印结果:无线死循环 哈哈

二分查找的错误写法

应该改成:

public class W {

    public static void main(String[] args) {
        int[] a = {1,2,3,4,5,6,7,8,9};
        int b = midSearch(a,0,a.length-1,7);
        System.out.println(a[b]);
    }

    public static int midSearch(int a[],int start,int end,int target){

        while (start <= end){
            int mid = (start+end)/2;
            if(a[mid] == target){
                return mid;
            }else if(a[mid] < target){
               start = mid + 1;
            }else{
               end = mid - 1;
            }
        }
        return -1;
    }
}

 打印结果:

二分查找的错误写法