Skip to content

Instantly share code, notes, and snippets.

@iMel408
Created March 24, 2019 19:26
Show Gist options
  • Save iMel408/fef98f67fcb4014385a5a16a8aefc8e9 to your computer and use it in GitHub Desktop.
Save iMel408/fef98f67fcb4014385a5a16a8aefc8e9 to your computer and use it in GitHub Desktop.
find position of a given int in an ordered list
ex_list = [0,1,2,3,4,5,6,7,8,9,10]
def binary_search(lst, num):
""" find position of a given int in an ordered list """
beg = 0
end = len(lst) - 1
while beg <= end:
mid = beg + (end - beg + 1) //2
if lst[mid] == num:
return mid
elif lst[mid] > num:
end = mid - 1
else:
beg = mid + 1
return None
print(binary_search(ex_list, 4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment