Classic algorithms · 1 / 22 Theory

Linear and binary search

An algorithm is a step-by-step recipe to solve a problem. Some are so useful that they are called classic. The most basic one is looking for an element in a list.

Linear search

It goes through the list from start to end until it finds the value. It works with any list, sorted or not:

def search(items, target):
    for i in range(len(items)):
        if items[i] == target:
            return i
    return -1

print(search([4, 8, 15, 16, 23], 15))  # 2
print(search([4, 8, 15, 16, 23], 5))   # -1

Returning -1 is a common convention for "not found", because no valid position is negative.

Binary search

If the list is sorted, you can do much better: look at the middle element. If it is smaller than the target, discard the left half; if it is larger, the right half. Repeat with the half that is left:

def binary_search(items, target):
    left = 0
    right = len(items) - 1
    while left <= right:
        middle = (left + right) // 2
        if items[middle] == target:
            return middle
        elif items[middle] < target:
            left = middle + 1
        else:
            right = middle - 1
    return -1

print(binary_search([1, 3, 5, 7, 9, 11, 13], 11))  # 5
print(binary_search([1, 3, 5, 7, 9, 11, 13], 4))   # -1

How much faster?

At each step binary search discards half of the elements. To search among a million elements, linear search needs up to 1,000,000 comparisons in the worst case; binary search, about 20:

import math

print(math.ceil(math.log2(1_000_000)))  # 20

But note: binary search requires the list to be sorted. If it is not, it gives wrong results.

Ready-made tools

Python has tools ready to use: in, list.index(x) (linear search) and the bisect module (binary search). Even so, coding them by hand is the best way to understand how they work:

from bisect import bisect_left

items = [1, 3, 5, 7, 9]
print(bisect_left(items, 7))  # 3

Practice with Linear search, Minimum and maximum by hand and Binary search.