Search algorithms
Linear search looks at the items one by one until it finds the right one. It's simple, but slow on a big list: with 1 million items, it can take 1 million comparisons.
Binary search only works on a sorted list: you look at the middle, discard the half that can't contain the value, and start again. With 1 million items, about twenty steps are enough!
def linear_search(items, target):
for i, item in enumerate(items):
if item == target:
return i
return -1
def binary_search(items, target):
low, high = 0, len(items) - 1
while low <= high:
mid = (low + high) // 2
if items[mid] == target:
return mid
if items[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
numbers = [3, 8, 15, 23, 42, 57, 91]
print(linear_search(numbers, 42))
print(binary_search(numbers, 42))
print(binary_search(numbers, 5))