top of page
About the Algorythm Recipe 🍰
This function takes a sorted array (arr) and a target element (target) as input. It then iteratively divides the search space in half until it finds the target element or concludes that it's not present in the array. If the target element is found, the function returns its index; otherwise, it returns -1.
Cookin' time! 🍳
def binary_search(arr, target):
"""
Perform binary search on a sorted array to find the target element.
Args:
- arr: Sorted list or array to search within.
- target: Element to search for.
Returns:
- Index of the target element if found, else -1.
"""
left, right = 0, len(arr) - 1
while left <= right:
mid = left + (right - left) // 2
# Check if target is present 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 the array
return -1
# Example usage:
arr = [2, 3, 4, 10, 40]
target = 10
result = binary_search(arr, target)
if result != -1:
print("Element is present at index", result)
else:
print("Element is not present in array")
bottom of page