-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathbinarysearch.js
More file actions
29 lines (24 loc) · 780 Bytes
/
binarysearch.js
File metadata and controls
29 lines (24 loc) · 780 Bytes
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
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid; // Target found, return the index
} else if (arr[mid] < target) {
left = mid + 1; // Target is in the right half
} else {
right = mid - 1; // Target is in the left half
}
}
return -1; // Target is not in the array
}
// Example usage:
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const target = 5;
const result = binarySearch(arr, target);
if (result !== -1) {
console.log(`Element ${target} found at index ${result}`);
} else {
console.log(`Element ${target} not found in the array`);
}