Binary Search Hacks
binary Search Homework Hacks
Problem 1 Code: Basic Binary Search
In order to view the answer highlight the code cell. (Styling Issue)
# Problem 1: Basic Binary Search
def binary_search_iterative(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
# Test for Problem 1
arr1 = [1, 3, 5, 7, 9, 11, 13]
target1 = 7
result1 = binary_search_iterative(arr1, target1)
print(f"Index of {target1}: {result1}")
Index of 7: 3
Problem 2 Code: Recursive Binary Search
In order to view the answer highlight the code cell. (Styling Issue)
# Problem 2: Recursive Binary Search
def binary_search_recursive(arr, target, left, right):
if left > right:
return -1
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search_recursive(arr, target, mid + 1, right)
else:
return binary_search_recursive(arr, target, left, mid - 1)
# Test for Problem 2
arr2 = [10, 20, 30, 40, 50, 60, 70, 80]
target2 = 30
result2 = binary_search_recursive(arr2, target2, 0, len(arr2) - 1)
print(f"Index of {target2}: {result2}")
Index of 30: 2