Sub topic 9
Tracing Nested Loops
This chapter assumes you can already build a trace table for a single loop, as covered in earlier chapters. It also assumes you can read 1-based pseudocode arrays, where A[1] is the first element. A nested loop is a loop whose body contains another loop. Tracing one is the same skill as tracing a single loop. The difference is that you have to track more state at once, and some of that state resets while some carries over.
How Nested Loops Execute
Each time the outer loop runs its body once, the inner loop runs through all of its iterations, from initialization to exit. Then control returns to the outer loop, which advances its own variable and starts the inner loop again from the beginning.
When you trace, keep two questions in mind:
- What resets? The inner loop variable is reinitialized on every outer iteration. Its starting value often depends on the outer variable.
- What carries over? Accumulators, such as counts and totals, and any array the loops modify keep their values across outer iterations.
Most tracing errors with nested loops come from mixing these two up. One mistake is to continue the inner variable from where it stopped last time. The other is to reset a running total that should keep growing.
A Triangular Loop: Counting Inversions
Start with a loop where the inner bound depends on the outer variable. An inversion is a pair of positions i < j where A[i] > A[j], meaning the two values are out of order.
FUNCTION CountInversions(A, n)
count ← 0
FOR i ← 1 TO n - 1 DO
FOR j ← i + 1 TO n DO
IF A[i] > A[j] THEN
count ← count + 1
END IF
END FOR
END FOR
RETURN count
END FUNCTIONTrace it with A = [4, 1, 3, 2] and n = 4. Give each inner-loop iteration its own row, and group the rows by the outer variable.
| i | j | A[i] | A[j] | A[i] > A[j] | count |
|---|---|---|---|---|---|
| - | - | - | - | - | 0 |
| 1 | 2 | 4 | 1 | true | 1 |
| 1 | 3 | 4 | 3 | true | 2 |
| 1 | 4 | 4 | 2 | true | 3 |
| 2 | 3 | 1 | 3 | false | 3 |
| 2 | 4 | 1 | 2 | false | 3 |
| 3 | 4 | 3 | 2 | true | 4 |
The function returns 4. Look at the shape of the trace. The inner loop runs 3 times, then 2, then 1. This is why it is called a triangular loop. Each new outer iteration starts j at i + 1, not at the value where j stopped before. count is never reset, because it was initialized outside both loops.
Notice also that the outer loop stops at n - 1. If it ran to n, the inner loop would be FOR j ← 5 TO 4, which runs zero times. That would be harmless here, but you should still recognize it as an empty range. An empty inner loop still counts as "running to completion". It just does nothing.
A Loop with a Data-Dependent Exit: Insertion Sort
The inner loop in insertion sort has no fixed count. It stops when the data says so, which makes it harder to trace.
PROCEDURE InsertionSort(A, n)
FOR j ← 2 TO n DO
key ← A[j]
i ← j - 1
WHILE i ≥ 1 AND A[i] > key DO
A[i + 1] ← A[i]
i ← i - 1
END WHILE
A[i + 1] ← key
END FOR
END PROCEDUREAND short-circuits. This means that once i ≥ 1 is false, A[i] is never evaluated, so the procedure never reads the nonexistent A[0].
Because the array changes during the run, add an action column that records each write. At the end of each outer iteration, add a snapshot row showing the whole array. Use one row per evaluation of the WHILE condition, including the final evaluation that is false.
Input: A = [4, 1, 3, 2], n = 4.
| j | key | i | condition | action | A after row |
|---|---|---|---|---|---|
| 2 | 1 | 1 | 1 ≥ 1 and 4 > 1: true | A[2] ← 4, i ← 0 | [4, 4, 3, 2] |
| 2 | 1 | 0 | 0 ≥ 1: false (short-circuit) | A[1] ← 1 | [1, 4, 3, 2] |
| 3 | 3 | 2 | 2 ≥ 1 and 4 > 3: true | A[3] ← 4, i ← 1 | [1, 4, 4, 2] |
| 3 | 3 | 1 | 1 ≥ 1 and 1 > 3: false | A[2] ← 3 | [1, 3, 4, 2] |
| 4 | 2 | 3 | 3 ≥ 1 and 4 > 2: true | A[4] ← 4, i ← 2 | [1, 3, 4, 4] |
| 4 | 2 | 2 | 2 ≥ 1 and 3 > 2: true | A[3] ← 3, i ← 1 | [1, 3, 3, 4] |
| 4 | 2 | 1 | 1 ≥ 1 and 1 > 2: false | A[2] ← 2 | [1, 2, 3, 4] |
The final array is [1, 2, 3, 4]. Several details in this trace are easy to get wrong:
- Duplicated values mid-shift are normal. Rows like
[4, 4, 3, 2]look like a bug, but they are not. The key is held safely inkeyuntil the final write. Do not "fix" the array in your table. - The inner variable is used after the loop.
A[i + 1] ← keydepends on the valueihad when theWHILEexited. Record that final value explicitly. Otherwise you will write the key to the wrong position. iis reinitialized fromj, not from its old value. At the start ofj = 3,ibecomes 2, even though it ended the previous iteration at 0.keyis read before any shifting. If you readA[j]from a later snapshot, you will pick up an already-shifted value.
The trace also gives you a cross-check. Insertion sort made 1 + 1 + 2 = 4 shifts, and CountInversions returned 4 on the same input. This is not a coincidence. Each shift fixes exactly one inverted pair. Matches like this between two independent traces are a cheap way to gain confidence in both.
Managing the Size of the Trace
Nested loops multiply the number of rows. A trace of n = 4 is fine. A trace of n = 10 is tedious and error-prone. Some strategies help:
- Keep inputs small but non-trivial. Three or four elements usually exercise every branch. Choose values so that the inner loop exits at different points: once immediately, once after several steps, once by running off the start of the array.
- Trace fully once, then summarize. After one complete outer iteration has confirmed your understanding, you can record later iterations as one summary line each: "j = 4: key 2 shifts past 4 and 3, lands at A[2]". Go back to full rows whenever something surprises you.
- Separate the layers visually. Leave a blank line or a ruled line between outer iterations, or use the snapshot rows as dividers.
- Check the loop shape before the values. Count the rows in each outer group and compare them with the ranges you predicted. Shape errors, such as a wrong bound or a missing reset, show up before you even look at the data.
Checking Your Trace Mechanically
After you finish a trace by hand, you can confirm it by running an instrumented version of the code. The Python version below pads the list with a dummy element at position 0, so its indices match the 1-based pseudocode and its output lines up with your table row for row.
def insertion_sort_trace(values):
A = [None] + list(values) # pad so A[1] is the first element, as in the pseudocode
n = len(values)
for j in range(2, n + 1):
key = A[j]
i = j - 1
while i >= 1 and A[i] > key:
A[i + 1] = A[i]
print(f"j={j} key={key} i={i}: {A[i]} > {key} true, shift -> {A[1:]}")
i = i - 1
if i >= 1:
print(f"j={j} key={key} i={i}: {A[i]} > {key} false, stop")
else:
print(f"j={j} key={key} i={i}: i >= 1 false, stop")
A[i + 1] = key
print(f" end of j={j}: {A[1:]}")
return A[1:]
print(insertion_sort_trace([4, 1, 3, 2]))Running it prints the same seven condition checks as the table, followed by [1, 2, 3, 4]. Use this to confirm a trace you have already done, not to replace it. The point of tracing by hand is to predict the output before you see it.
Exercises
Exercise
Trace InsertionSort on A = [3, 2, 1] with n = 3. How many times is the WHILE condition evaluated in total, and how many shifts happen?
Show answer
For j = 2, key = 2: at i = 1 the test 3 > 2 is true, so A[2] ← 3 and i becomes 0. At i = 0 the test is false, so A[1] ← 2, giving [2, 3, 1]. For j = 3, key = 1: at i = 2 the test 3 > 1 is true, so A[3] ← 3. At i = 1 the test 2 > 1 is true, so A[2] ← 2. At i = 0 the test is false, so A[1] ← 1, giving [1, 2, 3]. The condition is evaluated 2 + 3 = 5 times, and there are 3 shifts. This matches the 3 inversions in [3, 2, 1].
Exercise
Trace InsertionSort on the already-sorted array [1, 2, 3, 4]. What is the shape of the trace?
Show answer
Each outer iteration (j = 2, 3, 4) evaluates the WHILE condition exactly once. The condition is false every time, because A[j-1] < A[j]. No shifts happen, and each key is written back to the position it came from. The trace has 3 rows, one per outer iteration, so the inner loop's body never runs.
Exercise
A student writes CountInversions with the inner loop as FOR j ← 1 TO n instead of FOR j ← i + 1 TO n. What does it return for A = [4, 1, 3, 2], and why?
Show answer
It returns 6. The inner loop now visits every j, including j ≤ i. For distinct values, every unordered pair of positions is compared in both orders, and exactly one of the two orders satisfies A[i] > A[j]. Comparing a position with itself (j = i) is never true. So the function counts every pair once: 4 × 3 / 2 = 6, regardless of the order of the values. A trace shows the problem at once, because the group for i = 1 has 4 rows instead of 3.