手写二分查找

public class SearchElement {
    public static void main(String[] args) {
        //System.out.println("hello");
        int[] array = {1,2,3,4,5,6,7,8};
        int index = searchElement(array,0,7,100);
        int index2 = searchElement2(array,6);
        System.out.println(index2);
    }

    //二分查找 递归
    public static int searchElement(int array[], int low, int high, int target) {
        if (low > high) return -1;
        int mid = (low + high) / 2;
        if (array[mid] < target)
            return searchElement(array, mid + 1, high, target);
        if (array[mid]> target)
            return searchElement(array,low,mid-1,target);
        return mid;
    }

    //二分查找 不用递归
    public static int searchElement2(int[] array,int target){
        int low = 0;
        int high = array.length-1;
        while(low<=high){
            int mid = (low+high)/2;
            if(array[mid] > target){
                high = mid-1;
            }else if (array[mid]<target){
                low = mid + 1;
            }else{
                return mid;
            }
        }
        return -1;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_41590010/article/details/114682711