function binarySearch(arr, target) {
let lo = 0, hi = arr.length - 1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (arr[mid] === target) return mid;
arr[mid] < target ? (lo = mid + 1) : (hi = mid - 1);
}
return -1;
}Binary search halves the search space each step β O(log n), requires sorted input.
Binary Search is an efficient algorithm for finding a target in a sorted array. It works by repeatedly dividing the search space in half.
Time Complexity: O(log n) Space Complexity: O(1)
function binarySearch(arr: number[], target: number): number {
// Find the index of target in a sorted array
// Return -1 if not found
}
binarySearch([10, 20, 30, 40, 50], 30) // 2
binarySearch([10, 20, 30], 99) // -1