Counting the Work of Nested Iteration

The cost of nested loops is the sum of the inner work over each outer step. The inner amount can vary across steps.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace the triangular case
  2. Generalize the sum
  3. Write the inner limit for each outer iteration
  4. Read every independent limit from the problem

Trace the triangular case

For four items, choosing a second index strictly after the first gives counts 3, 2, 1, and 0. There are six pairs. Nested pair loops trace why each occurs once.

Generalize the sum

For \(n\) items the total is \(n(n-1)/2\). Doubling \(n\) roughly quadruples the pair work, whereas processing each item once roughly doubles it. Big-O bounds capture this difference for large inputs.[1]

Write the inner limit for each outer iteration

An algorithm examines all unordered pairs in a six-element array by comparing index \(i\) to each larger index. The inner loop runs five times at the start and zero times at the end. Each unordered pair is examined once, and no element is paired with itself. See ordered choices.

i           0  1  2  3  4  5
inner work  5  4  3  2  1  0
Total: 15 = 6×5/2

Read every independent limit from the problem

If the inner scan reads a second collection of length \(m\) for each of \(n\) items, the count may instead be \(nm\). If it can exit early, construct a worst-case input that forces all comparisons before writing that bound.

References

  1. Jeff Erickson, Algorithms ↩