from random import randint from timeit import Timer def sequential_search(a_list, item): pos = 0 while pos < len(a_list): if a_list[pos] == item: return True pos = pos + 1 return False def binary_search(a_list, item): first = 0 last = len(a_list) - 1 while first <= last: midpoint = (first + last) // 2 if a_list[midpoint] == item: return True elif item < a_list[midpoint]: last = midpoint - 1 else: first = midpoint + 1 return False #In order to enable the timer code to produce a random number to search for every time, it helps if #we create a small helper function that wraps the random # generator as part of what is timed. def linear_search_wrapper(data): item = randint(0,len(data)*2) #You have a 50% chance of looking for a value in the dataset sequential_search(data,item) def binary_search_wrapper(data): item = randint(0,len(data)*2) #You have a 50% chance of looking for a value in the dataset binary_search(data,item) #Test time for Linear Search #This is expected to be n print("linear_search() should be O(n)") for size in [1000,2000,1000000]: data = list(range(size)) t1 = Timer("linear_search_wrapper(data)", "from __main__ import linear_search_wrapper,data") print(f"linearSearch({size}) : {t1.timeit(number=1000)*1000:15.2f} microseconds") print() #Test time for Binary Search #This is expected to be n print("binary)search() should be O(log n)") for size in [1000,2000,1000000]: data = list(range(size)) t1 = Timer("binary_search_wrapper(data)", "from __main__ import binary_search_wrapper,data") print(f"binarySearch({size}) : {t1.timeit(number=1000)*1000:15.2f} microseconds") print()