Advertisement
johnpentyrch

CompareBinaryAndLinearSearch

May 3rd, 2020
666
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.89 KB | None | 0 0
  1. from timeit import timeit
  2. from random import randint
  3.  
  4.  
  5. def linear_search(alist,value):
  6.     for position, item in enumerate(alist):
  7.         #print(item, "is at position", position)
  8.         if item == value:
  9.             return position
  10.     return False
  11.  
  12. def binary_search(sorted_list, value):
  13.     left = 0
  14.     right = len(sorted_list) - 1
  15.     while left <= right:
  16.         mid = int((left + right)/2)
  17.         if sorted_list[mid] > value:
  18.             right = mid - 1
  19.         elif sorted_list[mid] < value:
  20.             left = mid + 1
  21.         else:
  22.             return mid
  23.     return False
  24.  
  25. #Create anonymous functions to use with timeit
  26. bs = lambda: binary_search(list_to_sort, value_to_find)
  27. ls = lambda: linear_search(list_to_sort, value_to_find)
  28.  
  29. print('List size:   Linear                 Binary            Ratio (linear/binary)')
  30.  
  31. for list_size in [5, 10,20,30,50,100,200,500,1000]:
  32.     slin=0
  33.     sbin=0
  34.     for i in range(100):
  35.         #sGenerate a large (1000 items) random list
  36.         list_to_sort = [randint(0,list_size) for i in range(list_size)]
  37.         #sort list
  38.         list_to_sort = sorted(list_to_sort)
  39.         #list_to_sort = [1,2,4,6,7,8,1,12,13,14]
  40.         value_to_find=randint(0,list_size)
  41.         slin+=timeit(ls, number = 100)
  42.         sbin+=timeit(bs, number = 100)
  43.  
  44.     print(list_size,(slin/100), (sbin/100), slin/sbin)
  45.  
  46. print('not found')
  47. for list_size in [5, 10,20,30,50,100,200,500,1000]:
  48.     slin=0
  49.     sbin=0
  50.     for i in range(100):
  51.         #sGenerate a large (1000 items) random list
  52.         list_to_sort = [randint(0,list_size) for i in range(list_size)]
  53.         #sort list
  54.         list_to_sort = sorted(list_to_sort)
  55.         #list_to_sort = [1,2,4,6,7,8,1,12,13,14]
  56.         value_to_find= 32.5#list_size+1
  57.         slin+=timeit(ls, number = 100)
  58.         sbin+=timeit(bs, number = 100)
  59.  
  60.     print(list_size,(slin/100), (sbin/100), slin/sbin)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement