Could someone explain how the Binary Search algorithm works with a simple Python example? #14996
Replies: 1 comment
|
Binary Search works on sorted arrays by repeatedly dividing the search interval in half. Here is a simple implementation: def binary_search(arr, x): |
0 replies
Answer selected by
ammiyo
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Binary Search works on sorted arrays by repeatedly dividing the search interval in half. Here is a simple implementation:
def binary_search(arr, x):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == x: return mid
elif arr[mid] < x: low = mid + 1
else: high = mid - 1
return -1