java 折半查找

java 折半查找

public static void main(String[] args) {
        int[] arr = {0,1,2,3,4,5,6,7,8,9,10};
        System.out.println(halfSearch_2(arr,5));
    }

    public static int halfSearch_1(int[] arr,int key){
        int min = 0,
            max = arr.length-1,
            mid = (min + max)/2;
        while (arr[mid] != key){
            if ( key > arr[mid])
                min = mid+1;
            else if (key < arr[mid])
                max = mid-1;
            if (min>max)
                return -1;
            mid = (min + max)/2;
        }
        return mid;
    }

    public static int halfSearch_2(int[] arr,int key){
        int min = 0,
            max = arr.length-1,
            mid;
        while (min<=max){
            mid = (max+min)>>1;
            if ( key > arr[mid])
                min = mid+1;
            else if (key < arr[mid])
                max = mid-1;
            else
                return mid;
        }
        return -1;
    }