Skip to content

Instantly share code, notes, and snippets.

@ehazlett
Created January 11, 2012 15:52
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 ehazlett/1595300 to your computer and use it in GitHub Desktop.
Save ehazlett/1595300 to your computer and use it in GitHub Desktop.
Find in Sorted
def find_in_sorted(arr, x):
'''
Returns index of x in arr
Precondition: arr is sorted
'''
def binsearch(start, end):
mid = start + (end - start) // 2
if start == end:
return -1
if x < arr[mid]:
return binsearch(start, mid)
elif x > arr[mid]:
if (mid == start):
return -1
return binsearch(mid, end)
else:
return mid
return binsearch(0, len(arr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment