Last active
May 31, 2020 02:38
-
-
Save rjperrella/ff73c3c7c69890b24e94dc311c9daa9c to your computer and use it in GitHub Desktop.
quick implementation of binary search in recursive python
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
# 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