import time, random, bisect
def linear_search(a, target):
for i in range(len(a)):
if a[i] == target:
return i
return -1
def binary_search(a, target):
low, high = 0, len(a) - 1
while low <= high:
mid = (low + high) // 2
if a[mid] == target:
return mid
elif a[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
random.seed(1)
for n in [10_000, 100_000, 1_000_000]:
a = list(range(0, 2 * n, 2)) # sorted even numbers
targets = [random.randrange(2 * n) for _ in range(100)]
for search in (linear_search, binary_search):
start = time.perf_counter()
for t in targets:
search(a, t)
ms = (time.perf_counter() - start) * 1000
print(n, search.__name__, round(ms, 2), "ms")
Your times will differ. On one computer the output was: linear search 28.63 ms, 243.88 ms and 2525.03 ms for n = 10 000, 100 000 and 1 000 000; binary search 0.17 ms, 0.26 ms and 0.5 ms.