Last active
August 14, 2019 02:49
-
-
Save mckelvin/3864616 to your computer and use it in GitHub Desktop.
the RIGHT Binary Search
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
""" | |
binary search | |
""" | |
def binary_search(num_array, x): | |
l = 0 | |
r = len(num_array) | |
while l < r: | |
mid = l + (r - l) / 2 | |
if num_array[mid] >= x: | |
r = mid | |
else: | |
l = mid + 1 | |
return l | |
if __name__ == '__main__': | |
assert 1 == binary_search([1], 9) | |
assert 0 == binary_search([1], -1) | |
assert 1 == binary_search([0, 1, 1, 3, 4, 5], 1) | |
assert 6 == binary_search([0, 1, 1, 3, 4, 5], 10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment