Checking every drawer

Linear Search

The analogy

You lost your keys, so you open every drawer in order until you find them. It works on any mess — nothing needs to be tidy — but if the keys are in the last drawer you opened them all.

Visualizer

Every drawer, one by one

step 1 / 10
5
3
8
1
9
2
7
4

Looking for 37. The data is in no particular order, so there is no clever shortcut available.

def linear_search(a, target):
    for i, v in enumerate(a):
        if v == target:
            return i
    return -1

# works on ANY order, zero preparation
# O(n) — and O(n) to prove absence
Check yourself

Linear search requires the data to be…