Skip to content

Instantly share code, notes, and snippets.

@nipuntalukdar
Created November 7, 2016 01:51
Show Gist options
  • Select an option

  • Save nipuntalukdar/238f2977238284b71332b512fe26e39b to your computer and use it in GitHub Desktop.

Select an option

Save nipuntalukdar/238f2977238284b71332b512fe26e39b to your computer and use it in GitHub Desktop.
Binary search in sorted array
def my_binary_search(lst, val, start, end):
if start == end:
if val == lst[start]:
return start
return -1
if val < lst[start] or val > lst[end]:
return -1
if val > lst[end]:
if val == lst[end]:
return end
elif val < lst[end]:
if val == lst[start]:
return start
mid = start + (end - start) /2
lret = my_binary_search(lst, val, start, mid)
if lret != -1:
return lret
rret = my_binary_search(lst, val, mid + 1, end)
return rret
position = my_binary_search('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'Y', 0, 25)
print position
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment