Created
November 17, 2020 17:35
-
-
Save giuscri/f4efcf107b376e5f52573c0f0cfa7011 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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