Created
February 3, 2015 18:52
-
-
Save mkowoods/9054b5ee311689ce119f to your computer and use it in GitHub Desktop.
Binary Search With Indexing
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
def BinarySearch(val, A, idx = None): | |
"""Recursive algorithm for performing binary search""" | |
#idx: the rightmost index based on the numbering of the original array | |
n = len(A) | |
if idx == None: | |
idx = (n - 1) | |
if n == 1: | |
if A[0] == val: | |
return idx | |
else: | |
return -1 | |
else: | |
split = n//2 | |
if A[split] > val: | |
idx -= (n - split) | |
return BinarySearch(val, A[:n//2], idx) | |
else: | |
return BinarySearch(val, A[n//2:], idx) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment