Advertisement
mrScarlett

binary and sequential search

Feb 1st, 2017
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.46 KB | None | 0 0
  1. import random
  2. import time
  3. numbers=[]
  4. x=0
  5. y=50
  6.  
  7. for num in range(16):
  8.     start = time.time()
  9.     temp = random.randint(x,y)
  10.     numbers.append(temp)
  11.     x+=50
  12.     y+=50
  13.     end = time.time()
  14.  
  15. print(numbers)
  16.  
  17. print(len(numbers))
  18.  
  19.  
  20. def binarySearch():
  21.     result = -1
  22.     first=0
  23.     last=len(numbers)
  24.     count=0
  25.     wanted=int(input("Enter your wanted value"))
  26.     while (first <= last and result==-1):
  27.         count+=1
  28.         mid = int((first+last)/2)
  29.         if (wanted == numbers[mid]):
  30.             result=mid
  31.             print("found!!")
  32.         else:
  33.             if (wanted<numbers[mid]):
  34.                 last = mid - 1
  35.                
  36.             else:
  37.                 first = mid+1
  38.     end = time.time()
  39.     print("item found at index position",result," Time:",end-start,"count ",count)
  40.     result = -1
  41.     first=0
  42.     last=len(numbers)
  43.     count=0
  44.  
  45. def sequentialSearch():
  46.     count=0
  47.     wanted=int(input("Enter your wanted value"))
  48.     start = time.time()
  49.     for x in range (len(numbers)):
  50.         if numbers[x]==wanted:
  51.             end = time.time()
  52.             print("item found at index position",numbers[x]," Time:",end-start,"count ",count)
  53.             break
  54.         else:
  55.             count+=1
  56.    
  57. while (True):
  58.     choice=input("A: Sequential Search or B: Binary search?")
  59.     if choice =="A":
  60.         sequentialSearch()
  61.     elif choice =="B":
  62.         binarySearch()
  63.     else:
  64.         break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement