Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Data Structures and Algorithms
  • What a Data Structure Is, and How Memory Works
  • Arrays and Dynamic Arrays: Full? Get a Box Twice the Size
  • Linked Lists: A Chain of Clues, Built in Python
  • Stacks: Last In, First Out, With the Undo Button
  • Queues: First In, First Out, With a Ring of Cells
  • Hash Tables: The Name Tells You Where to Look
  • Binary Search Trees: Smaller Left, Bigger Right, Half Gone at Every Look
  • Tree Traversals: In-Order, Pre-Order and Post-Order as a Tour of the House
  • Heaps and Priority Queues: Most Urgent First, Without Searching the Room
  • Graphs and Breadth-First Search (BFS): Fewest Hops, Level by Level
  • Big-O: Reading Cost From Code, With Handshakes and a Guest Book
  • Recursion: Russian Dolls, the Base Case and the Call Stack
  • Linear vs Binary Search: Page by Page, or Open in the Middle
  • Insertion Sort: Take the Next Card and Slide It Left Until It Fits
  • Merge Sort: Split the Pile, Then Merge Two Sorted Piles
  • Quick Sort: Line Up Around One Friend, Then Repeat on Each Side
  • Depth-First Search (DFS): Go Deep, Back Up, Mark Where You've Been
  • The Two Pointers Technique: Find a Pair in One Pass Instead of Every Pair
  • The Sliding Window Technique: One In, One Out
  • Greedy Algorithms: The Best-Looking Choice, Right Now
  • Dynamic Programming: Work It Out Once, Write It Down, Read It Back
  1. Blog
  2. /
  3. Data Structures and Algorithms
  4. /
  5. Algorithms

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Algorithms

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

Fifteen sorted words; check 1 at index 7 hat goes right, check 2 at index 11 lamp goes left, check 3 at index 9 jam goes right, check 4 at index 10 finds kite; words left before each check: 15, 7, 3, 1 antbeecatdogeggfoxgumhatinkjamkitelampmapnutowl 01234567891011121314 check 1: mid 7 = hat, k > h, go right (15 words) check 2: mid 11 = lamp, go left (7 words) check 3: mid 9 = jam, go right (3 words) check 4: mid 10 = kite, found (1 word)
Every check throws away half of what's left: 15, then 7, then 3, then 1.

Kite could be anywhere from lo 0 to hi 14.

  1. Check one: mid is (0 + 14) // 2 = 7, the word hat. h comes before k, so kite is on the right: lo becomes 8. Seven words left.
  2. Check two: mid is 11, lamp. l comes after k, so go left: hi becomes 10. Three words left.
  3. Check three: mid is 9, jam. j comes before k: lo becomes 10. One word left.
  4. 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

SearchCostA million words
LinearO(n)up to 1,000,000 checks
Binary (sorted list)O(log n)about 20 checks
Binary on an unsorted listwrong answerit 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Data Structures and Algorithms · 13 of 21

Previous
Recursion: Russian Dolls, the Base Case and the Call Stack
Next post
Insertion Sort: Take the Next Card and Slide It Left Until It Fits

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.

On this page

  • Finding a word in a dictionary
  • Binary search finds kite, step by step
  • The code
  • Halving is log n
  • Break it: words not A to Z
  • The cost
  • Where you meet it
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.