Skip to content

Instantly share code, notes, and snippets.

@kafagy
Created July 7, 2020 04:49
Show Gist options
  • Save kafagy/8dd85a611310878c923cf1a833285d95 to your computer and use it in GitHub Desktop.
Save kafagy/8dd85a611310878c923cf1a833285d95 to your computer and use it in GitHub Desktop.
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
# Check if x is present at mid
if arr[mid] < x:
low = mid + 1
# If x is greater, ignore left half
elif arr[mid] > x:
high = mid - 1
# If x is smaller, ignore right half
else:
return mid
# If we reach here, then the element was not present
return -1
# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10
# Function call
result = binary_search(arr, x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment