Skip to content

Instantly share code, notes, and snippets.

@lunaroyster
Created August 8, 2017 04:47
Show Gist options
  • Save lunaroyster/ce44d2670446f9adb9e31ce9ea71a16e to your computer and use it in GitHub Desktop.
Save lunaroyster/ce44d2670446f9adb9e31ce9ea71a16e to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# Python 2.7.6
# Authors: [thel3l, lunaroyster]
def binarySearch(sortedList, item, start=None, end=None):
#This happens when the item is not present in the array
if(start>end):
return(False)
#If start and end aren't defined, assume it's the entire array
if(start==None):
start = 0
if(end==None):
end = len(sortedList)-1
#Calc midpoint
midpoint = (start+end)/2
if(item == sortedList[midpoint]):
# We've found what we want
return(midpoint)
elif(item > sortedList[midpoint]):
# The item is greater than where we are. It must be in the second half of the array.
return(binarySearch(sortedList, item, midpoint+1, end))
elif(item < sortedList[midpoint]):
# The item is smaller than where we are. It must be in the first half of the array.
return(binarySearch(sortedList, item, start, midpoint-1))
# Test integers
ints = [1,2,3,4,5,6,7,8,9,10]
print(binarySearch(sortedList=ints, item=5))
# Test strings
strings = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"]
print(binarySearch(sortedList=strings, item="i"))
# Test floats
floats = [3.4, 4.1, 8.3, 9.4, 10.1, 12.8, 14.9, 15.1, 19.8, 21.7]
print(binarySearch(sortedList=floats, item=15.1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment