Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
https://repl.it/C75S/4 created by charles2588
#Binary Search
def binarysearch(arr,searchterm):
start=0 #we need start and end to calculate pivot
end=len(arr)-1
while(start<=end):#when to stop when start and end cross each other
pivot=int((start+end)/2)
if(arr[pivot])==searchterm:
return True
elif(arr[pivot]>searchterm):
end=pivot-1 #search left when pivot item is bigger
else:
start=pivot+1
return False
#Recursive Implementation of Bindary search
def recursivebinarysearch(arr,searchterm):
pivot=int(len(arr)/2)
if(pivot==0):
if(arr[pivot]!=searchterm):
return False
if(arr[pivot]==searchterm):
return True
elif(arr[pivot]>searchterm):
return recursivebinarysearch(arr[:pivot],searchterm)
else:
return recursivebinarysearch(arr[pivot+1:],searchterm)
print(binarysearch(sorted([1,5,8,2,4,-5,6,7]),8))
print(binarysearch(sorted([1,5,8,2,4,-5,6,7]),-5))
print(binarysearch(sorted([1,5,8,2,4,-5,6,7]),0))
print(recursivebinarysearch(sorted([1,5,8,2,4,-5,6,7]),8))
print(recursivebinarysearch(sorted([1,5,8,2,4,-5,6,7]),-5))
print(recursivebinarysearch(sorted([1,5,8,2,4,-5,6,7]),0))
Python 3.5.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
>>> True
True
False
True
True
False
=> None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.