TactivergeLite

Lite / Textbooks / Engineering Programming With Python / Chapter 6

6. Search, sort and cost

Version 1 · Technically checked (automated checks only) · 4 source lessons · Full interactive version

Introduction

Two correct programs can differ by a factor of a million in speed. Linear search checks every item; binary search on sorted data halves the range each step, so a million items need about twenty comparisons. Counting operations before timing them reveals how work grows with input size, and Big-O names that growth. Breadth-first search uses a queue to explore a grid map one ring at a time.

Figure 6.1. Halving beats walking (described in words)

Worst-case comparisons compared as bars: for 1,000 items linear search needs 1000 and binary search 10; for 1,000,000 items linear search needs 1000000 and binary search 20.

Explanation

Built from 4 School lessons. Each part is the lesson's own explanation.

A sorted catalogue lists a million part numbers. How many guesses do you need to find any one, or prove it isn't there?

Linear search

Check items from the start until you find the target or run out. It works on any list, sorted or not. Worst case: n comparisons (the target is last or absent). On average, for a present target, about n/2.

Binary search

Keep a range lo..hi. Compare the target with the middle item: equal, done; smaller, search the left half; bigger, the right half. Stop when the range is empty. It needs sorted data and fast access to any index (a list, not a file you must read line by line).

The cost of sorted

Binary search is only correct if the list really is sorted: on unsorted data it can confidently report 'not found' for an item that is there. If data arrives unsorted, you pay to sort it once (next lessons). Python's bisect module implements binary search for you.

Derivation: Why the worst case is ⌈log₂(n + 1)⌉ comparisons
  1. Each probe compares the target with the middle item of the current range. Either it matches, or the range shrinks to the left part or the right part, each holding at most half of what's left (excluding the middle item).

  2. Let N(k) be the largest list that binary search can always settle in k probes. With one probe you can settle a list of 1: N(1) = 1.

  3. With k probes, you spend one on the middle and must settle either side with k − 1 probes. So each side may hold N(k − 1) items: N(k) = 2·N(k − 1) + 1.

  4. Solving: N(1) = 1, N(2) = 3, N(3) = 7, N(4) = 15, and in general N(k) = 2^k − 1.

  5. So k probes suffice exactly when n ≤ 2^k − 1, that is 2^k ≥ n + 1. The smallest such k is ⌈log₂(n + 1)⌉.

  6. Example: n = 1,000 needs ⌈log₂ 1001⌉ = 10 probes (2¹⁰ − 1 = 1023 ≥ 1000). Doubling n adds just one probe.

Common mix-ups

Open the Lite lesson: Halve it again: binary search

6.2 Count the steps before you time them

Checking every pair of 1,000 waypoints for collisions: is that 1,000 checks, 500,000, or a million?

Single and nested loops

A loop over range(n) runs n times. A loop inside a loop multiplies: range(a) around range(b) runs a × b times. Three nested loops over n run n³ times. Loops one after another add: n + n = 2n.

When the inner loop depends on the outer

If the inner range uses i, add up the inner counts. range(i) gives 0 + 1 + … + (n − 1) = n(n − 1)/2; range(i, n) gives n + (n − 1) + … + 1 = n(n + 1)/2. A step, range(0, n, k), runs ⌈n/k⌉ times.

Count the expensive line

You don't need to count every statement. Pick the line that runs most often (a comparison, a distance calculation) and count that. Its formula dominates the program's cost as n grows.

Derivation: Why the triangular loop costs n(n − 1)/2
  1. The loop for i in range(n): for j in range(i): runs the inner body i times on pass i, for i = 0, 1, …, n − 1.

  2. Total S = 0 + 1 + 2 + … + (n − 1).

  3. Write the sum forwards and backwards and add: each column gives (n − 1), and there are n columns, so 2S = n(n − 1).

  4. Therefore S = n(n − 1)/2. For n = 1000: 1000 × 999 / 2 = 499,500.

  5. For large n this is about n²/2: still quadratic. Doubling n multiplies it by about 4.

Common mix-ups

Open the Lite lesson: Count the steps before you time them

6.3 Big-O: the shape of growth

Algorithm A takes 3n² + 50n + 1000 steps; algorithm B takes 400n. Which would you choose for a map with a million cells?

Keep the top term, drop the constant

From an exact count, keep the term that grows fastest and drop its coefficient: 5n + 20 → O(n); n(n − 1)/2 → O(n²); 4 log₂ n + 7 → O(log n). Big-O describes the shape of growth, not the exact number of steps.

The usual ladder

O(1) constant (dict lookup) < O(log n) (binary search) < O(n) (one scan) < O(n log n) (good sorts) < O(n²) (all pairs, insertion sort) < O(n³) (three nested loops). Doubling n adds a step, doubles, slightly more than doubles, quadruples, and multiplies by 8.

Predicting from a measurement

If you measure 20 ms at n = 1,000 and the code is O(n²), expect about 20 × 4 = 80 ms at n = 2,000 and 20 × 100 = 2 s at n = 10,000. Then test the prediction: if the measurement disagrees, your model of the code is wrong somewhere.

Derivation: Why constants and smaller terms are dropped
  1. Take T(n) = 3n² + 50n + 1000. Divide by n²: T(n)/n² = 3 + 50/n + 1000/n².

  2. As n grows, 50/n and 1000/n² shrink towards 0, so T(n)/n² approaches 3. The n² term ends up doing almost all the work.

  3. Big-O asks only how T grows, up to a constant factor: T(n) ≤ c·n² for some constant c once n is large enough (here c = 4 works for n ≥ 66). So T(n) is O(n²).

  4. The constant 3 is dropped because it depends on the machine and the language; the exponent 2 doesn't. Doubling n multiplies any O(n²) cost by about 4, whatever the constant.

Common mix-ups

Open the Lite lesson: Big-O: the shape of growth

6.4 Breadth-first search: a queue explores a map

Put a robot in a maze and flood it outwards one step at a time. Why does the first time the flood touches the goal give the shortest route?

The frontier is a queue

Start with the start cell in a queue. Repeatedly take the oldest cell, and add each unvisited free neighbour to the back. Because cells come out in the order they went in, every cell 1 move away is processed before any cell 2 moves away, and so on.

Visited set and came-from dict

Mark a cell visited when you add it to the queue, so it is never queued twice. Record came_from[neighbour] = current. When you reach the goal, follow came_from back to the start and reverse: that's the path.

Guarantees and limits

BFS always finds a path with the fewest moves if one exists, and reports failure after visiting every reachable cell if not. It ignores terrain cost: a short path through mud beats a long path on tarmac. Fixing that is Dijkstra's job in the term project.

Common mix-ups

Open the Lite lesson: Breadth-first search: a queue explores a map

Worked examples

Halve it again: binary search: example 1

Binary search that counts its comparisons, checked against linear search.

Solution

def binary_search(items, target):
    """Return (index or -1, comparisons) for a sorted list."""
    lo, hi, comparisons = 0, len(items) - 1, 0
    while lo <= hi:
        mid = (lo + hi) // 2
        comparisons += 1
        if items[mid] == target:
            return mid, comparisons
        if items[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1, comparisons


parts = list(range(1000, 1124, 4))     # 31 sorted part numbers
print(binary_search(parts, 1088))      # (22, 5)
print(binary_search(parts, 1090))      # (-1, 5)
worst = max(binary_search(parts, t)[1] for t in range(990, 1130))
print(worst)                           # 5, and ceil(log2(32)) = 5
Count the steps before you time them: example 1

Count the pair checks for n waypoints and confirm with the formula.

Solution

def pair_checks(n):
    count = 0
    for i in range(n):
        for j in range(i):        # each pair (j, i) with j < i, once
            count += 1
    return count


for n in [4, 10, 1000]:
    print(n, pair_checks(n), n * (n - 1) // 2)
# 4 6 6
# 10 45 45
# 1000 499500 499500
Big-O: the shape of growth: example 1

Predict from a measurement for three growth rates.

Solution

import math


def predict(t_ms, n_old, n_new, growth):
    f = {
        "n": lambda n: n,
        "n log n": lambda n: n * math.log2(n),
        "n^2": lambda n: n * n,
    }[growth]
    return t_ms * f(n_new) / f(n_old)


for g in ["n", "n log n", "n^2"]:
    print(g, round(predict(20, 1024, 4096, g), 1))
# n 80.0
# n log n 96.0
# n^2 320.0
Breadth-first search: a queue explores a map: example 1

BFS on a text map, returning the path as a list of cells.

Solution

from collections import deque


def bfs(rows, start, goal):
    """Fewest-move path from start to goal on a map of strings ('#' = wall), or [] if none."""
    h, w = len(rows), len(rows[0])
    queue = deque([start])
    came_from = {start: None}          # doubles as the visited set
    while queue:
        cell = queue.popleft()
        if cell == goal:
            path = []
            while cell is not None:
                path.append(cell)
                cell = came_from[cell]
            return path[::-1]
        r, c = cell
        for n in [(r - 1, c), (r, c + 1), (r + 1, c), (r, c - 1)]:
            nr, nc = n
            if 0 <= nr < h and 0 <= nc < w and rows[nr][nc] != "#" and n not in came_from:
                came_from[n] = cell
                queue.append(n)
    return []


grid = ["....",
        ".##.",
        "...."]
path = bfs(grid, (1, 0), (1, 3))
print(len(path) - 1, path)    # 5 [(1, 0), (0, 0), (0, 1), (0, 2), (0, 3), (1, 3)]
print(bfs([".#.", "##.", "..."], (0, 0), (2, 2)))   # []

Interactive figures, in words

Figure 6.2 from Halve it again: binary search

With 31 parts, pick a target and step both searches one comparison at a time. Try a part near the end and one that isn't stocked. Then switch to 127 parts: how much worse does linear search get? And binary?

The visualiser shows a sorted list of part numbers as a strip of cells. Linear search colours cells one by one from the left. Binary search probes the middle, then the middle of the remaining half, shading the range still in play. With 31 parts binary search never needs more than 5 comparisons; linear search may need 31.

Figure 6.3 from Count the steps before you time them

Turn on only n and n² and slide n from 2 to 1,000. Read the 'when n doubles' column. Then add n log n and log n. Which growth would your collision check (all pairs) follow?

The plotter draws operation counts against n for log n, n, n log n and n², and a table gives each count and the factor it grows by when n doubles: about 1 extra step for log n, 2 for n, a little over 2 for n log n and 4 for n².

Figure 6.4 from Breadth-first search: a queue explores a map

Keep Breadth-first search selected and step through the first 20 expansions. Notice the 'rings' of equal move count. Then wall off the goal completely and watch what BFS does. Finally, add walls to make the path as long as you can.

The planner shows a 7 × 10 grid with a start on the left and a goal on the right, a wall in column 5 rows 1 to 5, and a rough patch. BFS expands cells in rings of increasing move count and returns a fewest-moves path around the end of the wall. Walling off the goal makes BFS expand every reachable cell and report no path.

The interactive versions are in the full chapter.

Laboratory

These run in a browser on the full site (they need a faster connection). Simulations are simplified educational models.

Practice

Each question links to its Lite lesson, where your answer is checked on our server and a wrong answer gets a hint. Answers are never sent to your device.

  1. A sorted list holds 500 part numbers. Binary search compares the target with one middle element per loop and halves the range each time. In the worst case (including a target that is not there), how many elements does it compare with the target?
    Answer it in “Halve it again: binary search”
  2. Binary search runs on the unsorted list [40, 10, 30, 20] looking for 40. What happens?
    Answer it in “Halve it again: binary search”
  3. A student writes 'while lo < hi:' instead of 'while lo <= hi:'. What goes wrong?
    Answer it in “Halve it again: binary search”
  4. A program is comparing every pair of waypoints. Its step count is measured with: count = sum(1 for i in range(0, 266, 10)). What value does count hold?
    Answer it in “Count the steps before you time them”
  5. One loop over n readings filters spikes; a second loop over n readings averages them. How many loop passes in total?
    Answer it in “Count the steps before you time them”
  6. Which list is in order from slowest-growing to fastest-growing?
    Answer it in “Big-O: the shape of growth”
  7. What would change if BFS used a stack (pop the newest cell) instead of a queue?
    Answer it in “Breadth-first search: a queue explores a map”
  8. The goal is completely surrounded by walls. What does BFS do?
    Answer it in “Breadth-first search: a queue explores a map”

Engineering applications

Look-up tables

Embedded systems often store calibration curves as sorted tables. Binary search finds the right segment in a handful of steps, fast enough to run every millisecond on a small microcontroller.

Path planning

Warehouse robots and game characters plan routes on grids. Breadth-first search finds the shortest route in steps; weighted versions add the cost of rough terrain or slow aisles.

Watch (optional)

Streaming video uses a lot of data. Everything you need is in the text.

Summary

Glossary

Lists and indexing
A list is an ordered, changeable collection written in square brackets. Items are numbered from 0, and negative indices count back from the end. Field Guide
for loops and range
A for loop runs its body once for each item of a sequence. range(start, stop, step) produces whole numbers from start up to but not including stop. Field Guide
while loops
A while loop repeats its body as long as its condition stays true, checking the condition before each pass. Field Guide

Project: Measure the growth

Implement linear search, binary search and a nested-loop duplicate finder. Count operations for input sizes from 100 to 100,000, plot the counts on suitable axes, and check each curve against the Big-O you predicted.

Deliverables

Write it up on paper or in your own notes. Lite never stores what you write.

References

Further reading from the lessons

← 5. Modules, objects and data structures7. Numerical methods →