Skip to content

Instantly share code, notes, and snippets.

@giuscri
Created November 17, 2020 17:35
Show Gist options
  • Save giuscri/f4efcf107b376e5f52573c0f0cfa7011 to your computer and use it in GitHub Desktop.
Save giuscri/f4efcf107b376e5f52573c0f0cfa7011 to your computer and use it in GitHub Desktop.
from typing import List
def bsearch(A: List[int], x: int) -> int:
if not A:
return -1
i, j = 0, len(A)-1
while i <= j:
mid = i+(j-i)//2
if A[mid] == x:
return mid
elif x < A[mid]:
i, j = i, mid-1
else:
i, j = mid+1, j
return -1
def test_bsearch():
assert bsearch([], 42) == -1
assert bsearch([42], 42) == 0
assert bsearch([1, 42], 42) == 1
assert bsearch([i for i in range(43)], 42) == 42
assert bsearch([i for i in range(43)], 100) == -1
assert bsearch([i for i in range(43)], -100) == -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment