Skip to content

Instantly share code, notes, and snippets.

@beyonddream
Last active November 16, 2022 05:42
Show Gist options
  • Save beyonddream/c73f6f57b1d10172dd08c47fce8e6540 to your computer and use it in GitHub Desktop.
Save beyonddream/c73f6f57b1d10172dd08c47fce8e6540 to your computer and use it in GitHub Desktop.
binary search in python
#!/usr/bin/env python3
from typing import List
def binary_search(arr: List[int], target: int) -> int:
"""
>>> arr = [3, 6, 12, 18]
>>> target = 12
>>> binary_search(arr, target)
"""
low, high = 0, len(arr) - 1
while low <= high:
mid = low + (high - low) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment