0

我是 Javascript 新手,我想知道是否有任何现有的 Javascript 库包含类似于 C++ equal_range 的二进制搜索功能?我写了一个我正在寻找的快速实现:

/*
 * Javascript version of C++ equal_range via lower_bound and upper_bound
 *
 * Input: The array A in ascending order and a target T
 * Output: The tightly bound indices [i, j] where A[i] <= T < A[j] if T exists in A
 * otherwise [-1, -1] is returned if T does not exist in A
 */

let lowerBound = (A, T) => {
    let N = A.length,
        i = 0,
        j = N - 1;
    while (i < j) {
        let k = Math.floor((i + j) / 2);
        if (A[k] < T)
            i = k + 1;
        else
            j = k;
    }
    return A[i] == T ? i : -1;
};

let upperBound = (A, T) => {
    let N = A.length,
        i = 0,
        j = N - 1;
    while (i < j) {
        let k = Math.floor((i + j + 1) / 2);
        if (A[k] <= T)
            i = k;
        else
            j = k - 1;
    }
    return A[j] == T ? j + 1 : -1;
};

let equalRange = (A, T) => {
    return [lowerBound(A, T), upperBound(A, T)];
};
4

1 回答 1

0

Google 闭包库可能是迄今为止我发现的最接近的库:

https://google.github.io/closure-library/api/goog.array.html

于 2020-07-07T02:28:01.410 回答