Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2020
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1. from timeit import timeit
  2. from random import randint
  3.  
  4. list_to_search = [i for i in range(1000000)]
  5. value = 30
  6.  
  7. def linear_search(list_to_search, value):
  8.     for i in range(len(list_to_search)):
  9.         if list_to_search[i] == value:
  10.             return
  11.  
  12. def binary_search(list_to_search, value):
  13.     left = 0
  14.     right = len(list_to_search)-1
  15.     while left <= right:
  16.         mid = int((left+right)/2)
  17.         if list_to_search[mid] > value:
  18.             right = mid - 1
  19.         elif list_to_search[mid] < value:
  20.             left = mid + 1
  21.         else:
  22.             return mid
  23.  
  24.     return False
  25.    
  26. position = binary_search(list_to_search, value)
  27.  
  28. if position !=- 1:
  29.     print(str(value),"found at position", position)
  30. else:
  31.     print("not found")
  32.  
  33.  
  34. ls = lambda: linear_search(list_to_search, randint(0,1000000))
  35. bs = lambda: binary_search(list_to_search, randint(0,1000000))
  36.  
  37. #time the functions for 100 runs each
  38. print("Linear search took:")
  39. print(timeit(ls, number = 100))
  40.  
  41. print("Binary search took:")
  42. print(timeit(bs, number = 100))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement