美文网首页
二分法实现

二分法实现

作者: qpan | 来源:发表于2018-03-26 23:25 被阅读11次

    package android.util
    class ContainerHelpers 实现二分法的帮助类(循环实现法)

    在 Arrays.binarySearch()也可找到示例

    // This is Arrays.binarySearch(), but doesn't do any argument validation.
        static int binarySearch(int[] array, int size, int value) {
            int lo = 0;
            int hi = size - 1;
            while (lo <= hi) {
                final int mid = (lo + hi) >>> 1;
                final int midVal = array[mid];
                if (midVal < value) {
                    lo = mid + 1;
                } else if (midVal > value) {
                    hi = mid - 1;
                } else {
                    return mid;  // value found
                }
            }
            return ~lo;  // value not present
        }
    
        static int binarySearch(long[] array, int size, long value) {
            int lo = 0;
            int hi = size - 1;
            while (lo <= hi) {
                final int mid = (lo + hi) >>> 1;
                final long midVal = array[mid];
                if (midVal < value) {
                    lo = mid + 1;
                } else if (midVal > value) {
                    hi = mid - 1;
                } else {
                    return mid;  // value found
                }
            }
            return ~lo;  // value not present
        }
    

    相关文章

      网友评论

          本文标题:二分法实现

          本文链接:https://www.haomeiwen.com/subject/pkbdcftx.html