二进制优化搜索

时间:2015-06-03 21:57:45

标签: java optimization binary-search

我正在尝试编写一个函数来使用二进制细分来优化函数。我的想法是,我可以传递它的下限和上限进行测试,它将返回从函数返回“true”的n的最小值。

public interface BinaryTest {
    boolean test(int n);
}

/**
 * Returns the smallest int in the set lower <= n <= upper that returns true for
 * {@link BinaryTest#test(int)}. If a value 'n' returns true, then any value
 * > 'n' will also return true.
 *
 * If none of the values return true, return -1.
 */
int optimizeSmallest(int lower, int upper, BinaryTest testFunction) {
    // ???
}

虽然二进制搜索的例子很常见,但是找到模式更加困难,而且我觉得很容易出现一个错误的错误。

optimizeSmallest函数会是什么样的?

简单的测试用例:

    for (int i = 0; i < 10; i++) {
        int j = i;
        int r = BinarySearch.optimizeSmallest(0, 10, (n) -> {
            return n > j;
        });

        assertEquals(i + 1, r);
    }

3 个答案:

答案 0 :(得分:2)

int optimizeSmallest(int lower, int upper, BinaryTest testFunction) {
    if (lower > upper || !testFunction.test(upper)) {
        return -1;
    }
    while (lower != upper) {
        int middle = (lower + upper) / 2;
        if (testFunction.test(middle)) {
            upper = middle;
        } else {
            lower = middle + 1;
        }
    }
    return lower;
}

答案 1 :(得分:1)

尝试:

int optimizeSmallest(int lower, int upper, BinaryTest testFunction) {
    if(lower >= upper) {
        return upper;
    }
    int mid = (low + high) >>> 1;
    return testFunction.test(mid) ? optimizeSmallest(lower, mid, testFunction) 
        : optimizeSmallest(mid, upper, testFunction);
}

答案 2 :(得分:1)

这不是最佳的(它会在某些情况下第二次测试最终值),但似乎适用于我抛出的所有测试用例。我会留在这里直到有人发布一个比这个更好的答案。

public static int optimizeSmallest(int lower, int upper, BinaryTest testFunction) {
    while (lower < upper) {
        int mid = (lower + upper) >>> 1;

        if (testFunction.test(mid))
            upper = mid;
        else
            lower = mid + 1;
    }

    return testFunction.test(lower) ? lower : -1;
}