-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.ts
55 lines (52 loc) · 1.18 KB
/
index.ts
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
export function binarySearch(
haystack: number[],
needle: number,
left: number = 0,
right: number = haystack.length - 1
): number | undefined {
while (left <= right) {
const middle = Math.floor((left + right) / 2);
if (haystack[middle] < needle) {
left = middle + 1;
} else if (haystack[middle] > needle) {
right = middle - 1;
} else {
return middle;
}
}
}
export function binarySearchLeftmost(
haystack: number[],
needle: number,
left: number = 0,
right: number = haystack.length
) {
while (left < right) {
const middle = Math.floor((left + right) / 2);
if (haystack[middle] < needle) {
left = middle + 1;
} else {
right = middle;
}
}
return left;
}
export function binarySearchRightmost(
haystack: number[],
needle: number,
left: number = 0,
right: number = haystack.length
) {
while (left < right) {
const middle = Math.floor((left + right) / 2);
if (haystack[middle] > needle) {
right = middle;
} else {
left = middle + 1;
}
}
return right - 1;
}
// const array = [3, 3];
// console.log(binarySearchLeftmost(array, 3));
// console.log(binarySearchRightmost(array, 3));