Java二分查找代码案例

 

 

第一种写法spa

public static int binarySearch(Integer[] srcArray, int des) {code

    //定义初始最小、最大索引索引

    int low = 0;static

    int high = srcArray.length - 1;while

    //确保不会出现重复查找,越界co

    while (low <= high) {return

        //计算出中间索引值search

        int middle = (high + low)>>>1 ;//防止溢出arc

        if (des == srcArray[middle]) {

            return middle;

        //判断下限

        else if (des < srcArray[middle]) {

            high = middle - 1;

        //判断上限

        else {

            low = middle + 1;

        }

    }

    //若没有,则返回-1

    return -1;

}

第二种写法:

public int find (long[] strs , long searchKey) {         int lowerBound = 0;         int upperBound = strs.length -1;         int curInt;         while (true) {             curInt = (upperBound - lowerBound)/2;             if (strs[curInt]==searchKey) {                 return curInt;             } else if (lowerBound>upperBound){                 return strs.length;             } else {                 if (strs[curInt] < searchKey) {                     lowerBound =curInt+1;                 }else {                     upperBound=curInt-1;                 }             }         }     }

相关文章
相关标签/搜索