Skip to content

Instantly share code, notes, and snippets.

@hillscottc
Created May 31, 2014 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hillscottc/2b2baa3a6f77827fd662 to your computer and use it in GitHub Desktop.
Save hillscottc/2b2baa3a6f77827fd662 to your computer and use it in GitHub Desktop.
Binary search of a string.
def binarySearch(alist, item):
first = 0
last = len(alist)-1
found = False
while first<=last and not found:
midpoint = (first + last)//2
if alist[midpoint] == item:
found = True
else:
if item < alist[midpoint]:
last = midpoint-1
else:
first = midpoint+1
return found
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(binarySearch(testlist, 3))
print(binarySearch(testlist, 13))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment