Skip to content

Instantly share code, notes, and snippets.

@firephil
Created March 5, 2018 21:33
Show Gist options
  • Save firephil/1395a1aab8e0c49f99eb8d541e38dfa0 to your computer and use it in GitHub Desktop.
Save firephil/1395a1aab8e0c49f99eb8d541e38dfa0 to your computer and use it in GitHub Desktop.
Simple Binary Search on a sorted list
def binarySearch(list, item):
first = 0
last = len(list) - 1
while first <= last:
i = (first + last) // 2
if list[i] == item:
return (item,i)
elif list[i] > item:
last = i - 1
elif list[i] < item:
first = i + 1
else:
return (item,-1)
def main():
ls = [x for x in range(1,11)]
print(ls)
(element,index) = binarySearch(ls, 5)
print("index : %s element: %s" %(index, element))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment