Created
May 20, 2018 20:58
-
-
Save scriptpapi/f70793f4ccc55ef17b5ba07f5b92bb9a to your computer and use it in GitHub Desktop.
Simple implementation of Binary Search algorithm in Python
This file contains hidden or 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
# Simple implementation of Binary Search algorithm | |
# Sorting included | |
from math import ceil | |
def Bsearch(item, list): | |
s_index = int(ceil(len(list)/2)) | |
list.sort() | |
found = False | |
while True: | |
try: | |
if item == list[s_index]: | |
found = True | |
break | |
else: | |
if item > list[s_index]: | |
del list[:s_index] | |
else: | |
del list[s_index:] | |
s_index = int(ceil(len(list) / 2)) | |
except IndexError: | |
found = False | |
break | |
print(list) | |
return found | |
# Test Case | |
test = [4, 6, 2, 6, 8, 9, 3, 5, 7, 11, 46, 74, 97] | |
print(Bsearch(13, test)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment