Complete the code to initialize the middle index in the binary search loop.
let mid = Math.floor((low + [1]) / 2);
The middle index is calculated by taking the floor of the average of low and high indices.
Complete the code to update the low index when the target is greater than the middle element.
if (target > arr[mid]) { low = [1]; }
When the target is greater than the middle element, we move the low index to mid + 1 to search the right half.
Fix the error in the loop condition to correctly continue searching while low is less than or equal to high.
while (low [1] high) { // binary search steps }
The loop should continue while low is less than or equal to high to cover all elements.
Fill both blanks to correctly update the high index when the target is less than the middle element.
if (target < arr[mid]) { high = [1]; low = [2]; }
When target is less than middle element, high moves to mid - 1 and low stays the same.
Fill all three blanks to complete the binary search function that returns the index of the target or -1 if not found.
function binarySearch(arr: number[], target: number): number {
let low = 0;
let high = arr.length - 1;
while (low [1] high) {
let mid = Math.floor((low + high) / 2);
if (arr[mid] === target) {
return [2];
} else if (target < arr[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return [3];
}The loop condition is low <= high. Return mid if found, else return -1 if not found.