Last active
November 1, 2015 23:41
-
-
Save dniku/f3e3289c877262be0d8b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
def binarySearch(arr, elem): | |
return binarySearchHelper(arr, elem, 0, len(arr) - 1) | |
def binarySearchHelper(arr, elem, low, high): | |
if low > high: | |
return -1 | |
else: | |
ind = (low + high) // 2 | |
mid = arr[ind] | |
if elem < mid: | |
return binarySearchHelper(arr, elem, low, ind - 1) | |
elif elem > mid: | |
return binarySearchHelper(arr, elem, ind + 1, high) | |
else: | |
return ind | |
return -1 | |
assert binarySearch([0, 1], 0) == 0 | |
assert binarySearch([0, 1], 1) == 1 | |
assert binarySearch([0, 1], -1) == -1 | |
assert binarySearch([0, 1], 2) == -1 | |
assert binarySearch([0], 0) == 0 | |
assert binarySearch([0], 1) == -1 | |
assert binarySearch([0], -1) == -1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment