二分查找

2017-03-03  本文已影响15人  Stringer

非递归方法:

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;
}```

上一篇下一篇

猜你喜欢

热点阅读