Complete the code to calculate the middle index in the binary search.
def binary_search(arr, target, low, high): if low > high: return -1 mid = (low [1] high) // 2 if arr[mid] == target: return mid elif arr[mid] < target: return binary_search(arr, target, mid + 1, high) else: return binary_search(arr, target, low, mid - 1)
The middle index is found by adding low and high, then dividing by 2.
Complete the code to check if the target is found at the middle index.
def binary_search(arr, target, low, high): if low > high: return -1 mid = (low + high) // 2 if arr[mid] [1] target: return mid elif arr[mid] < target: return binary_search(arr, target, mid + 1, high) else: return binary_search(arr, target, low, mid - 1)
We check if the element at mid is equal to the target.
Fix the error in the recursive call when the target is greater than the middle element.
def binary_search(arr, target, low, high): if low > high: return -1 mid = (low + high) // 2 if arr[mid] == target: return mid elif arr[mid] < target: return binary_search(arr, target, [1], high) else: return binary_search(arr, target, low, mid - 1)
When target is greater, search the right half starting from mid + 1.
Fill both blanks to complete the recursive call when the target is less than the middle element.
def binary_search(arr, target, low, high): if low > high: return -1 mid = (low + high) // 2 if arr[mid] == target: return mid elif arr[mid] < target: return binary_search(arr, target, mid + 1, high) else: return binary_search(arr, target, [1], [2])
When target is less, search the left half from low to mid - 1.
Fill all three blanks to create a complete recursive binary search function.
def binary_search(arr, target, [1], [2]): if [1] > [2]: return -1 mid = ([1] + [2]) // 2 if arr[mid] == target: return mid elif arr[mid] < target: return binary_search(arr, target, mid + 1, [2]) else: return binary_search(arr, target, [1], mid - 1)
The function uses low and high as the search boundaries. The base case checks if low is greater than high. Mid is calculated using low and high. Recursive calls adjust low and high accordingly.
