Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # iterative binary search
- def binary_search(array, target):
- l, r = 0, len(array)-1
- while l <= r:
- middle = (l + r) // 2
- potential_match = array[middle]
- if target == potential_match:
- return middle
- elif target < potential_match:
- r = middle - 1
- else:
- l = middle + 1
- return -1
- # Example usage
- arr = [1, 2, 3, 10, 40]
- print(binary_search(arr, 10)) # Output: 3
- print(binary_search(arr, 0)) # Output: -1
Advertisement
Add Comment
Please, Sign In to add comment