Linear vs Binary Search: Page by Page, or Open in the Middle
Is kite a real word? Page by page takes 11 checks; opening in the middle takes 4. Trace binary search step by step, see a million words answered in 20 checks, and watch it give the wrong answer on an unsorted list.
What you will learn
- Explain linear and binary search with a paper dictionary
- Trace binary search with lo, hi and mid until the word is found
- Say why binary search needs about log n checks: a million words in twenty
- Show why binary search gives a wrong answer on a list that is not sorted
Before you start
- Big-O: Reading Cost From Code
- Arrays and Dynamic Arrays
Emma is making a spelling game. Tom types "kite", and the game must answer: is it a real word? It looks the word up in its word list, sorted A to Z. A real dictionary has about a million words, and if the game checks them one by one, Tom waits, and waits.
So count the checks, two ways. Same word, same answer. What changes is the number of checks: 11 one way, 4 the other.
Finding a word in a dictionary
Imagine a paper dictionary. One way is page by page: a, b, c, d, until you reach k. That's eleven looks. That's linear search.
The smarter way is to open it in the middle. You land on h. k comes after h, so kite must be in the right half: throw the left half away. The middle of what's left is l, and k comes before l, so go left. Then j: go right. Then k. Found it in four looks. That's binary search. It only works because a dictionary is sorted A to Z.
Binary search finds kite, step by step
Kite could be anywhere from lo 0 to hi 14.
- Check one: mid is (0 + 14) // 2 = 7, the word hat. h comes before k, so kite is on the right:
lobecomes 8. Seven words left. - Check two: mid is 11, lamp. l comes after k, so go left:
hibecomes 10. Three words left. - Check three: mid is 9, jam. j comes before k:
lobecomes 10. One word left. - Check four: mid is 10, and it's kite. Found.
The code
checks = 0
def find(words, target):
global checks
for i in range(len(words)):
checks += 1
if words[i] == target:
return i
return -1 # not in the dictionary
That's linear search: one loop from the first word to the last, returning the index or -1 for not found. A word near the end costs almost n checks.
checks = 0
def find(words, target):
global checks
lo, hi = 0, len(words) - 1
while lo <= hi:
mid = (lo + hi) // 2
checks += 1
if words[mid] == target:
return mid # found it
if words[mid] < target:
lo = mid + 1 # kite is on the right
else:
hi = mid - 1 # kite is on the left
return -1
That's binary search. lo and hi mark the part of the list where the word can still be, and mid is its middle. Python compares strings A to Z, so words[mid] < target means the middle word comes first and you keep the right half.
import binary_search
import linear_search
words = ["ant", "bee", "cat", "dog", "egg",
"fox", "gum", "hat", "ink", "jam",
"kite", "lamp", "map", "nut", "owl"]
a = linear_search.find(words, "kite")
print(f"Linear: kite at {a} after {linear_search.checks} checks")
b = binary_search.find(words, "kite")
print(f"Binary: kite at {b} after {binary_search.checks} checks")
Linear: kite at 10 after 11 checks
Binary: kite at 10 after 4 checks
Halving is log n
The number of checks is how many times you can halve the list before one word is left. Fifteen words, four checks. A thousand words, ten. A million words, twenty. Double the words and binary search needs just one more check. That number is log n.
import binary_search
import linear_search
for n in (1_000, 10_000, 100_000, 1_000_000):
words = []
for i in range(n):
words.append(f"word{i:07d}")
last = words[n - 1]
linear_search.checks = 0
binary_search.checks = 0
linear_search.find(words, last)
binary_search.find(words, last)
print(f"{n:9,d} words: linear {linear_search.checks:9,d}"
f" binary {binary_search.checks:2d}")
1,000 words: linear 1,000 binary 10
10,000 words: linear 10,000 binary 14
100,000 words: linear 100,000 binary 17
1,000,000 words: linear 1,000,000 binary 20
The words are already A to Z, and it looks for the last one, the hardest case for linear search. A thousand times more words, and binary needs just ten more checks. A word that isn't there at all costs linear search every check; binary search keeps halving until nothing is left, so about twenty again.
Break it: words not A to Z
import binary_search
import linear_search
words = ["kite", "ant", "map", "owl",
"dog", "egg", "cat"] # not A to Z
b = binary_search.find(words, "kite")
print(f"Binary: kite at {b}")
a = linear_search.find(words, "kite")
print(f"Linear: kite at {a}")
Binary: kite at -1
Linear: kite at 0
Kite is the very first word, but binary search says it isn't there. It trusts the order. The middle word is owl, and o comes after k, so it throws away the right half. Then the middle of what's left is ant, a comes before k, so it throws away the left part, and kite was in it. Linear search finds it at index 0. Binary search only works on a sorted list: sort it first, then search. Sorting is the next topic, starting with insertion sort.
The cost
| Search | Cost | A million words |
|---|---|---|
| Linear | O(n) | up to 1,000,000 checks |
| Binary (sorted list) | O(log n) | about 20 checks |
| Binary on an unsorted list | wrong answer | it throws away the wrong half |
The same halving idea is what makes a binary search tree fast.
Where you meet it
- A spell checker keeps its word list A to Z, so a word is found in a handful of checks.
- The contacts on your phone are kept sorted, so finding one doesn't mean reading them all.
- Guess the number: say the middle, hear higher or lower, and half the numbers are gone.
- Finding the change that broke a program: developers test the middle version, then keep halving.
Try it yourself
Look for "owl" and then for "zebra" in the 15-word list. Predict both check counts for each search before you run it.
Related courses on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Data Structures and Algorithms Concepts: No Coding Needed
How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)Related posts
Big-O: Reading Cost From Code, With Handshakes and a Guest Book
Big-O asks one question: how do the steps grow when the list grows? Check a school trip sheet for duplicates two ways, handshakes and a guest book, count every step in Python, then grow the list to ten thousand ids and watch 10,000 steps turn into almost 50 million.
Recursion: Russian Dolls, the Base Case and the Call Stack
Recursion means doing the same job on a smaller piece of the problem, and stopping at a base case. Count Emma's Russian dolls with a Python function that calls itself, watch each call wait on the call stack so the answers come back in reverse, then take the base case out and meet RecursionError.
Insertion Sort: Take the Next Card and Slide It Left Until It Fits
Emma's hand 7, 3, 9, 2, 5 sorted one card at a time in 6 shifts. Trace each card, see why a backwards hand costs the most, why 5,000 shuffled cards need over 6 million shifts, and why a sorted hand needs zero.
Merge Sort: Split the Pile, Then Merge Two Sorted Piles
Ms Kate's eight exam papers sorted in 24 steps: split in half until each pile is one paper, then merge sorted piles by taking the lower top. A million papers take about 20 million steps, and the price is extra room.
