Skip to content

Instantly share code, notes, and snippets.

@mkowoods
Created February 3, 2015 18:52
Show Gist options
  • Save mkowoods/9054b5ee311689ce119f to your computer and use it in GitHub Desktop.
Save mkowoods/9054b5ee311689ce119f to your computer and use it in GitHub Desktop.
Binary Search With Indexing
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