In: Computer Science
Draw a single graph in Python showing the performance of both a linear and binary search algorithm against the number of elements (100,000). Consider the worst case scenario. In the graph we want to see: labeling of the axes, a legend, a title and the graphs for both linear and binary search, again correctly labeled. Explain what you see. Hint: Use Plot Functions (Plot Chart, series from functions) from the H!de Editor.
#source code:
import timeit
import matplotlib.pyplot as plt
def l_search(list,element):
check=False
for i in range(len(list)):
if(list[i]==10):
check=True
break
else:
pass
if(check==True):
return "Found"
else:
return "not found"
def b_search(list,left,right,element):
if(right>=left):
mid=int(left+(right-left)/2)
if(list[mid]==element):
return
element
elif(list[mid]>element):
return
b_search(list,left,mid-1,element)
else:
return
b_search(list,mid+1,right,element)
else:
return "not found"
if __name__=="__main__":
#check time taken binary search worst scenario last elements
list_number=[i for i in range(1,100000)]
check_element=99999
start=timeit.timeit()
b=b_search(list_number,0,len(list_number)-1,check_element)
if(b=="not found"):
print("not found")
else:
print("found")
end=timeit.timeit()
b_time=end-start
print(b_time)
#check time taken linear search worst scenario last elements
start=timeit.timeit()
print(l_search(list_number,check_element))
end=timeit.timeit()
l_time=end-start
print(l_time)
plt.subplot(1,2,1)
plt.title("Binary search")
plt.xlabel("Element")
plt.ylabel("Time Taken")
plt.plot(check_element,b_time,"ro")
plt.legend()
plt.subplot(1,2,2)
plt.title("Linear search")
plt.xlabel("Element")
plt.ylabel;("Time Taken")
plt.plot(check_element,l_time,"ro")
plt.legend()
plt.show()
#output:
#if you have any doubt comment below..