function binarySearch(arr: number[], target: number, left: number, right: number): number {
if (left > right) return -1;
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
else if (arr[mid] > target) return binarySearch(arr, target, left, mid - 1);
else return binarySearch(arr, target, mid + 1, right);
}
const array = [1, 3, 5, 7, 9, 11];
const result = binarySearch(array, 7, 0, array.length - 1);
console.log(result);The array is [1, 3, 5, 7, 9, 11]. The target 7 is at index 3 (0-based). The recursive binary search finds it and returns 3.
function binarySearch(arr: number[], target: number, left: number, right: number): number {
if (left > right) return -1;
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
else if (arr[mid] > target) return binarySearch(arr, target, left, mid - 1);
else return binarySearch(arr, target, mid + 1, right);
}
const array = [2, 4, 6, 10, 12];
const result = binarySearch(array, 8, 0, array.length - 1);
console.log(result);The target 8 is not in the array. The recursive calls eventually cross over (left > right), so the function returns -1.
Binary search halves the search space each call. For 64 elements (2^6), the worst-case recursion depth is log₂(64) + 1 = 7 calls total (6 recursive calls + initial).
function binarySearch(arr: number[], target: number, left: number, right: number): number {
if (left >= right) return -1;
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
else if (arr[mid] > target) return binarySearch(arr, target, left, mid - 1);
else return binarySearch(arr, target, mid + 1, right);
}
const array = [1, 3, 5, 7];
const result = binarySearch(array, 7, 0, array.length - 1);
console.log(result);The base case uses 'left >= right' which causes the function to return -1 prematurely when left equals right, missing the last element check. So it returns -1 even if the target is present.
function firstOccurrence(arr: number[], target: number, left: number, right: number): number {
if (left > right) return -1;
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
if (mid === 0 || arr[mid - 1] < target) return mid;
else return firstOccurrence(arr, target, left, mid - 1);
} else if (arr[mid] < target) {
return firstOccurrence(arr, target, mid + 1, right);
} else {
return firstOccurrence(arr, target, left, mid - 1);
}
}
const array = [1, 2, 4, 4, 4, 5, 6];
const result = firstOccurrence(array, 4, 0, array.length - 1);
console.log(result);The function finds the first index where 4 appears by checking if the previous element is less than 4 or if it's the first element. The first occurrence of 4 is at index 2.