Advertisement
Guest User

Untitled

a guest
Sep 19th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.32 KB | None | 0 0
  1. from sort import quicksort
  2. from plot import XYPlot
  3.  
  4. dataLin = []
  5. dataBin = []
  6. def linearsearch(A, key):
  7.     n = 0
  8.     for i in range(len(A)):
  9.         n += 1
  10.         if A[i] == key:
  11.             return n
  12.            
  13.     raise KeyError("item not found")
  14.  
  15. for i in range(2,101):
  16.     listLin = range(1,i)
  17.     #print listLin
  18.     keyLin = len(listLin)
  19.     nLin = linearsearch(listLin, keyLin)
  20.     dataLin= dataLin+ [(i,nLin)]
  21.  
  22. def binarysearch(A, key):
  23.     lo = 0
  24.     hi = len(A) - 1
  25.     n = 0
  26.  
  27.     while lo <= hi:
  28.         mid = (lo + hi)/2
  29.         n += 1
  30.  
  31.         if A[mid] < key:
  32.             lo = mid + 1
  33.            
  34.         elif A[mid] > key:
  35.             hi = mid - 1
  36.            
  37.         else:
  38.             return n
  39.        
  40.     raise KeyError("value not in list!")
  41.  
  42.  
  43. for j in range(2,101):
  44.     listBin = range(1,j)
  45.     listBin = quicksort(listBin)
  46.     #print listBin
  47.     keyBin = 1
  48.     nBin = binarysearch(listBin, keyBin)
  49.     dataBin= dataBin+ [(j, nBin)]
  50.    
  51. p = XYPlot(x_label="Number of entries in data", y_label="Number of steps required to achieve reach final point of worst case", title="Number of steps required to achieve worst case scenario for binary search and linear search")
  52. p.add_series(dataLin, label="Linear Search")
  53. p.add_series(dataBin, label="Binary Search")
  54. p.show()
  55.  
  56. print("Exit")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement