Last active
June 30, 2022 16:55
-
-
Save claytonjwong/53bd1c1489b12eccad176addb8afd8e0 to your computer and use it in GitHub Desktop.
Javascript version of C++ equal_range via lower_bound and upper_bound
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Javascript version of C++ equal_range via lower_bound and upper_bound | |
* | |
* Gist: https://gist.github.com/claytonjwong/53bd1c1489b12eccad176addb8afd8e0 | |
*/ | |
let lowerBound = (A, T) => { | |
let N = A.length, | |
i = 0, | |
j = N; | |
while (i < j) { | |
let k = Math.floor((i + j) / 2); | |
if (A[k] < T) | |
i = k + 1; | |
else | |
j = k; | |
} | |
return i; | |
}; | |
let upperBound = (A, T) => { | |
let N = A.length, | |
i = 0, | |
j = N; | |
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 : j; | |
}; | |
let equalRange = (A, T) => { | |
return [lowerBound(A, T), upperBound(A, T)]; | |
}; | |
let i, j; | |
let A = [1, 1, 2, 2, 3, 3, 5, 5]; | |
// 0 1 2 3 4 5 6 7 8 | |
let T = 2; | |
[i, j] = equalRange(A, T); | |
console.log(`${T} in range ${i}..${j}`); // 2 in range 2..4 | |
T = 4; | |
[i, j] = equalRange(A, T); | |
console.log(`${T} in range ${i}..${j}`); // 4 in range 6..6 |
really helpful!
Actually I wrote this before I realized lodash (https://lodash.com/) provides this JS functionality for us:
- lower bound is available as
_.sortedIndex
๐ https://lodash.com/docs/#sortedIndex - upper bound is available as
_.sortedLastIndex
๐ https://lodash.com/docs/#sortedLastIndex
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
really helpful!