Skip to content

Instantly share code, notes, and snippets.

@gerep
Last active January 21, 2022 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerep/5f008256e0afe4b8d84d2900063bfe59 to your computer and use it in GitHub Desktop.
Save gerep/5f008256e0afe4b8d84d2900063bfe59 to your computer and use it in GitHub Desktop.
Binary search
def binary_search(target, arr):
low = 0
high = len(arr) - 1 # it starts with index 0
while low <= high:
mid = (low + high) // 2 # it represents the index of the middle element
if arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return low != len(arr) and arr[low] == target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment