java二分法查找实现代码

时间:2022-03-04 00:00:47
package util;

class BinarySearch {
    static int binarySearch(int[] array,int goal){//传入排好序的数组和目标数字
        int low = 0;//数组的开始项
        int high = array.length - 1;//数组的结束项
        while(low <= high)
        {
            int middle = (low + high) / 2;//数组分割数
            if(goal == array[middle])
            {
                return middle;
            }
            if(goal > array[middle])
            {
                low = middle + 1;
            }
            if(goal < array[middle])
            {
                high = middle - 1;
            }
        }
        return -1;
    }
    
}