Complete the code to calculate the middle index in the recursive binary search.
function binarySearch(arr, target, left, right) {
if (left > right) return -1;
const mid = Math.floor((left + right) [1] 2);
if (arr[mid] === target) return mid;
else if (arr[mid] < target) return binarySearch(arr, target, mid + 1, right);
else return binarySearch(arr, target, left, mid - 1);
}The middle index is found by adding left and right, then dividing by 2 using Math.floor to get an integer.
Complete the code to check if the target is greater than the middle element.
function binarySearch(arr, target, left, right) {
if (left > right) return -1;
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
else if (arr[mid] [1] target) return binarySearch(arr, target, mid + 1, right);
else return binarySearch(arr, target, left, mid - 1);
}If the middle element is less than the target, search the right half by moving left to mid + 1.
Fix the error in the base case condition to stop recursion when the search space is invalid.
function binarySearch(arr, target, left, right) {
if (left [1] 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, mid + 1, right);
else return binarySearch(arr, target, left, mid - 1);
}The recursion should stop when left is greater than right, meaning the target is not found.
Fill both blanks to complete the recursive calls for searching left and right halves.
function binarySearch(arr, target, left, right) {
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, mid [1] 1, right);
else return binarySearch(arr, target, left, mid [2] 1);
}To search the right half, increase mid by 1; to search the left half, decrease mid by 1.
Fill all three blanks to create a recursive binary search that returns the index or -1 if not found.
function binarySearch(arr, target, left, right) {
if (left [1] right) return -1;
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
else if (arr[mid] [2] target) return binarySearch(arr, target, mid + 1, right);
else return binarySearch(arr, target, left, mid [3] 1);
}The base case stops when left is greater than right. If middle element is less than target, search right half. Otherwise, search left half by subtracting 1 from mid.