

Binary search is an efficient algorithm used to search for a target value within a sorted array or list. Here's an explanation of how the binary search algorithm works:
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
# Check if target is found at mid
if arr[mid] == target:
return mid
# If target is greater, ignore left half
elif arr[mid] < target:
left = mid + 1
# If target is smaller, ignore right half
else:
right = mid - 1
# If target is not found in array
return -1
Explanation:
left and right, to the start and end indices of the array, respectively.mid = (left + right) // 2.arr[mid]) with the target value:
mid.mid is less than the target, we update left to mid + 1 to search in the right half of the array.mid is greater than the target, we update right to mid - 1 to search in the left half of the array.left is greater than right, indicating that the target is not found in the array.Time Complexity:
The time complexity of binary search is \(O(\log n)\), where \(n\) is the size of the input array.