Skip to content

binarySearch

DevGod
DevGod
Vtuber
function binarySearch(arr, target) {
let left = 0, right = arr.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid; // Found
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1; // Not found
}