Coding Towards The Answer, Part 12
Seek And Ye Shalt Find…
4 min readOct 26, 2023
We have in Traversing The Tree, that we could conduct tree search with Depth-First Search (DFS) and Breadth-First Search (BFS). Here we demonstrate other means.
Binary Search
def binary_search_recursive(arr, target, low, high):
if low > high:
return -1
mid = low + ((high - low) // 2) # deters overflow instead of: (low + high) // 2
if arr[mid] == target:
return mid # Found the target element, return index
elif target < arr[mid]:
return binary_search_recursive(arr, target, low, mid - 1) # Search the left half
else:
return binary_search_recursive(arr, target, mid + 1, high) # Search the right half
return -1 # Element not found
def binary_search_iterative(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = low + ((high - low) // 2)
if arr[mid] == target:
return mid…