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.

๐Ÿ“– In depth โ€” the full reference

Linear search โ€” everything worth knowing

factvaluenote
worst / average caseO(n) / ~n/2 probesevery drawer might need opening
best caseO(1)first drawer
requirement on dataNONEits entire superpower โ€” unsorted, linked, streamed: all fine
when it WINSsmall n, one-off searchessorting first costs O(n log n) โ€” pointless for a single lookup
when it losesrepeated searches on big datasort once + binary search, or hash it
variant: sentinel searchplant target at the endremoves the bounds check per step โ€” a real micro-optimisation from the textbooks

Python: the built-ins ARE linear search

xs = [4, 2, 7, 2]
print(7 in xs)           # True  โ€” linear scan, O(n)
print(xs.index(2))        # 1     โ€” first match, ValueError if absent
print(xs.count(2))        # 2     โ€” full scan, always O(n)

# first match with a condition โ€” the generator idiom:
first_even = next((x for x in xs if x % 2 == 0), None)

# `x in big_list` inside a loop is the hidden O(n^2) from m0l9 โ€”
# a set makes the same test O(1).
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โ€ฆ

Practice โ€” write it yourself

linear_search(arr, t) checks every drawer one by one: return the first index holding t, or -1. No sorting required โ€” that is the point.

Python 3 ยท runs in your browser ยท your draft is saved locally
๐Ÿ“ My notessaved in this browser