美文网首页
二分查找

二分查找

作者: Stringer | 来源:发表于2017-03-03 15:13 被阅读15次

    非递归方法:

    public static int binarySearch(int[] a,int x){
            int low=0;
            int high=a.length-1;
            while(low<=high){
                int middle=(low+high)/2;
                if(x==a[middle]){
                    return middle;
                }else if(x<a[middle]){
                    high=middle-1;
                }else{
                    low=middle+1;
                }
            }
            return -1;
        }```
    
    递归方法:
    

    public static int binarySearch2(int[] a,int x,int low,int high){
    if(low<=high){
    int middle=(low+high)/2;
    if(x==a[middle]){
    return middle;
    }else if(x<a[middle]){
    return binarySearch2(a,x,low,middle-1);
    }else{
    return binarySearch2(a,x,middle+1,high);
    }
    }
    return -1;
    }```

    相关文章

      网友评论

          本文标题:二分查找

          本文链接:https://www.haomeiwen.com/subject/tnzjmttx.html