Skip to content

Instantly share code, notes, and snippets.

@scriptpapi
Created May 20, 2018 20:58
Show Gist options
  • Save scriptpapi/f70793f4ccc55ef17b5ba07f5b92bb9a to your computer and use it in GitHub Desktop.
Save scriptpapi/f70793f4ccc55ef17b5ba07f5b92bb9a to your computer and use it in GitHub Desktop.
Simple implementation of Binary Search algorithm in Python
# 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