forked from yangshun/lago
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binarySearch.js
55 lines (52 loc) · 1.28 KB
/
binarySearch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* Returns the leftmost position that `target` should go to such that the
* sequence remains sorted.
* @param {number[]} arr
* @param {number} target
* @return {number} Position
*/
function bisectLeft(arr, target) {
let left = 0;
let right = arr.length;
while (left < right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
/**
* Returns the rightmost position that `target` should go to such that the
* sequence remains sorted.
* @param {number[]} arr
* @param {number} target
* @return {number} Position
*/
function bisectRight(arr, target) {
let left = 0;
let right = arr.length;
while (left < right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] > target) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
/**
* Searches for a target element within an array.
* Returns -1 if the target is not found.
* @param {number[]} arr
* @param {number} target
* @return {number} The index of the target element within the array.
*/
function binarySearch(arr, target) {
const idx = bisectLeft(arr, target);
return idx < arr.length && arr[idx] === target ? idx : -1;
}
export { bisectLeft, bisectRight, binarySearch };