Created
June 30, 2016 05:45
-
-
Save charles2588/56d6253f4696875434051c49e56e6390 to your computer and use it in GitHub Desktop.
https://repl.it/C75S/4 created by charles2588
This file contains 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
#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)) | |
This file contains 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
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