Created
March 5, 2018 21:42
-
-
Save firephil/50d9c6b86d08337ba4111209747c5ca5 to your computer and use it in GitHub Desktop.
With Basic Error Handling Range Check
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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