Why Nesting Depth Alone Does Not Give the Cost
Nested loops can do little repeated work when their total number of advances is bounded by input length.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace two advancing positions
For two sorted lists, a merge repeatedly compares their heads and consumes one. No consumed value is revisited. A program written with one loop around a helper that advances a pointer can still perform linear total advances. See merging sorted parts.
Count across all outer steps
If a pointer resets to the start for every item, the argument fails. Try to bound all pointer movements together before multiplying apparent loop lengths. Counting nested work shows the contrasting case of fully repeated scans.[1]
Sum the changing lengths instead of multiplying identical bounds
An outer loop runs with lengths eight, four, two and one while its inner loop scans the current length. Total visits are fifteen. Seeing two syntactic levels does not give a quadratic bound because the inner work shrinks geometrically. See halving.
Outer length 8 4 2 1
Inner visits 8 4 2 1
Total visits 15 = 2×8 - 1
Distinguish calls that partition from calls that repeat
If every item belongs to exactly one group and an inner loop walks that group's members, total inner visits equal the total number of members. If each group rescans the full dataset, multiplicative work returns. Count which elements are actually revisited.