Skip to content

Instantly share code, notes, and snippets.

@firephil
Created March 5, 2018 21:42
Show Gist options
  • Save firephil/50d9c6b86d08337ba4111209747c5ca5 to your computer and use it in GitHub Desktop.
Save firephil/50d9c6b86d08337ba4111209747c5ca5 to your computer and use it in GitHub Desktop.
With Basic Error Handling Range Check
def binarySearch(list, item):
first = 0
last = len(list) - 1
if item < list[first] or item > list[last]:
return (item,-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*10 for x in range(1,11)]
print(ls)
(element,index) = binarySearch(ls, -10)
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