-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-search.ts
More file actions
48 lines (44 loc) · 1.11 KB
/
Copy pathbinary-search.ts
File metadata and controls
48 lines (44 loc) · 1.11 KB
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
/**
* Performs a binary search on a sorted array to find the index of the target value.
*
* The function assumes that the input array is sorted in ascending order.
* It repeatedly divides the search interval in half until the target is found
* or the interval is empty.
*
* @param arr - A sorted array of numbers (ascending order).
* @param target - The number to search for in the array.
* @returns The index of the target if found; otherwise, -1.
*
* @example
* binarySearch([1, 3, 5, 7, 9], 5);
* // Returns: 2
*
* @example
* binarySearch([1, 3, 5, 7, 9], 4);
* // Returns: -1
*/
export function binarySearch(
arr: number[],
target: number,
left?: number,
right?: number,
): number {
let l = left ? left : 0,
r = right ? right : arr.length - 1;
let mid = (arr.length / 2) | 0;
if (arr.length === 0) return -1;
if (arr[l] === target) return l;
if (arr[r] === target) return r;
while (l < r) {
if (arr[mid] === target) {
return mid;
} else if (mid < target) {
r = mid - 1;
mid = ((l + r) / 2) | 0;
} else if (mid > target) {
l = mid + 1;
mid = ((r - l) / 2) | 0;
}
}
return -1;
}