Skip to content

Instantly share code, notes, and snippets.

@dniku
Last active November 1, 2015 23:41
Show Gist options
  • Save dniku/f3e3289c877262be0d8b to your computer and use it in GitHub Desktop.
Save dniku/f3e3289c877262be0d8b to your computer and use it in GitHub Desktop.
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