Created
March 5, 2018 21:33
-
-
Save firephil/1395a1aab8e0c49f99eb8d541e38dfa0 to your computer and use it in GitHub Desktop.
Simple Binary Search on a sorted list
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 | |
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