java二分法查找实现代码

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

  

转载于:https://www.cnblogs.com/caoleiCoding/p/8901343.html

你可能感兴趣的:(java二分法查找实现代码)