Sub topic 9
Tracing Nested Loops
This chapter assumes you can already trace a single loop with a trace table and read 1-based array pseudocode. A nested loop is a loop placed inside the body of another loop. For each pass of the outer loop, the inner loop runs completely, from its start to its exit. Most tracing mistakes in nested loops come from losing track of which loop you are in, or from forgetting to reset the inner loop's variables when the outer loop advances.
The Example: Insertion Sort
Insertion sort has an outer FOR loop that picks the next element, called the key. Its inner WHILE loop shifts larger elements one place to the right until it finds the spot where key belongs.
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 here. When i reaches 0, the test stops early and A[0] is never read.
Organising the Trace Table
Give every evaluation of the inner condition its own row. Group the rows by the outer variable j, and record the array after each change. Here is the trace for A = [4, 1, 3] with n = 3.
| j | key | i | i ≥ 1 AND A[i] > key | action | A after |
|---|---|---|---|---|---|
| 2 | 1 | 1 | 4 > 1 true | A[2] ← 4, i ← 0 | [4, 4, 3] |
| 2 | 1 | 0 | false (i ≥ 1 fails) | A[1] ← 1 | [1, 4, 3] |
| 3 | 3 | 2 | 4 > 3 true | A[3] ← 4, i ← 1 | [1, 4, 4] |
| 3 | 3 | 1 | 1 > 3 false | A[2] ← 3 | [1, 3, 4] |
Notice that i starts again at j - 1 on every outer pass. If your trace carries the old i forward from the previous pass, you have skipped the reset step.
Common Errors
- Skipping the reset. Inner-loop variables such as
iandkeyare reassigned at the top of every outer iteration. Write those reassignments as their own entries in the trace. - Stopping the inner loop early. The inner loop exits only when its condition is false. Write down the final false test every time, because the exit value of
idecides wherekeygoes. - Reading stale array values. A shift changes
Ain place, so the next comparison reads the updated array. Keep the "A after" column current. - Off-by-one on the inner bounds. Check the first and last values the inner variable takes on each outer pass. Here
iruns fromj - 1down to 0 at most.
Checking a Hand Trace
After you finish a trace by hand, you can confirm it with a short program. This program prints the array after each outer pass. Python indexes from 0, so the bounds are shifted down by one.
def insertion_sort(a):
for j in range(1, len(a)):
key = a[j]
i = j - 1
while i >= 0 and a[i] > key:
a[i + 1] = a[i]
i -= 1
a[i + 1] = key
print(f"j={j + 1}: {a}")
insertion_sort([4, 1, 3])
# j=2: [1, 4, 3]
# j=3: [1, 3, 4]Exercise
Trace InsertionSort on A = [3, 2, 1] with n = 3. How many shifts (executions of A[i + 1] ← A[i]) happen in total, and how many times is the inner WHILE condition evaluated?
Show answer
For j = 2, key = 2. The test at i = 1 is true (3 > 2), so A becomes [3, 3, 1]. The test at i = 0 is false, and A[1] ← 2 gives [2, 3, 1]. For j = 3, key = 1. The test at i = 2 is true (3 > 1), giving [2, 3, 3]. The test at i = 1 is true (2 > 1), giving [2, 2, 3]. The test at i = 0 is false, and A[1] ← 1 gives [1, 2, 3]. There are 3 shifts in total, and the condition is evaluated 5 times (2 times for j = 2, then 3 times for j = 3).
Exercise
A learner's trace for A = [4, 1, 3] shows i = 0 at the start of the j = 3 pass. What step did they skip, and what goes wrong as a result?
Show answer
They skipped the assignment i ← j - 1 at the top of the outer loop. With i = 0, the inner test fails at once, and A[1] ← 3 overwrites the 1. The array becomes [3, 4, 3] instead of [1, 3, 4].