Skip to content

Instantly share code, notes, and snippets.

@rjperrella
Last active May 31, 2020 02:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjperrella/ff73c3c7c69890b24e94dc311c9daa9c to your computer and use it in GitHub Desktop.
Save rjperrella/ff73c3c7c69890b24e94dc311c9daa9c to your computer and use it in GitHub Desktop.
quick implementation of binary search in recursive python
# Not efficient - this is better done as a while loop (unless Python can optimize tail-recursion...)
# return index of item.
# assumes arry is in ascending order.
# return -1 if item is not found in the array.
# interestingly, the bug I had where line 10 had high - low/ 2 still gave correct answers because the array was so small (and
# perhaps also it was the dimensions?
def bsearch(arry, low, high, item):
if low > high:
return -1 # not found
mid = high + low // 2
if item == arry[mid]:
return mid
if item < arry[mid]:
return bsearch(arry, low, mid-1, item)
else:
return bsearch(arry, mid+1, high, item)
a = [1,3,5,6,7,9]
assert(2 ==bsearch(a, 0, len(a)-1, 5))
assert(-1 ==bsearch(a, 0, len(a)-1, 4))
assert(5 ==bsearch(a, 0, len(a)-1, 9)) # should be 5
assert(0 ==bsearch(a, 0, len(a)-1, 1)) # should be 0
print("passed unit tests")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment