Sub topic 2
From Problem Statement to Pseudocode with Stepwise Refinement
This chapter assumes you know the conventions from the previous chapter: ← for assignment, FOR/WHILE blocks closed by END, and arrays indexed from 1.
Refining a Problem Statement
Stepwise refinement means you write the solution as a few coarse steps first. Then you expand each step until every line maps to one simple operation. Take the problem "return the largest value in a non-empty array."
Level 1:
- Treat the first element as the best so far.
- Compare each remaining element with the best and keep the larger one.
- Return the best.
Level 2 turns each step into precise pseudocode:
FUNCTION FindMax(A, n)
max ← A[1]
FOR i ← 2 TO n DO
IF A[i] > max THEN
max ← A[i]
END IF
END FOR
RETURN max
END FUNCTIONBuilding a Trace Table
A trace table has one column for each variable and each tested condition. It gets one row per step. You fill it in by executing the pseudocode by hand.
Input: A = [3, 7, 2, 9], n = 4
step | i | A[i] | A[i] > max | max
-----+---+------+------------+----
init | - | - | - | 3
1 | 2 | 7 | true | 7
2 | 3 | 2 | false | 7
3 | 4 | 9 | true | 9
Returns 9Tracing Loops
Write one row per iteration, and record the condition test even when it fails. Most termination bugs show up at that final failing check. For a FOR loop, also note when the loop variable passes its bound.
Tracing Nested Loops
For nested loops, add a column for each loop variable. Write one row per inner iteration, so the outer variable repeats down the table. Here is insertion sort on A = [3, 1, 2]:
| j | key | i | A[i] > key | A after step |
|---|---|---|---|---|
| 2 | 1 | 1 | true, shift | [3, 3, 2] |
| 2 | 1 | 0 | stop (i < 1) | [1, 3, 2] |
| 3 | 2 | 2 | true, shift | [1, 3, 3] |
| 3 | 2 | 1 | false | [1, 2, 3] |
Picking Inputs Worth Tracing
One normal input rarely exposes a bug. Choose inputs that push each loop to its limits:
| Input type | What it tests |
|---|---|
| n = 1 | Loop body runs zero times |
| Target at first or last position | Boundary indexes |
| Already sorted / reverse sorted | Inner loop runs zero or the maximum number of times |
| Duplicates | Strict `>` versus `≥` comparisons |
Exercise
Trace FindMax with A = [5], n = 1. How many times does the loop body run, and what is returned?
Show answer
Zero times. FOR i ← 2 TO 1 has an empty range, so max stays A[1] and the function returns 5.
Exercise
Trace insertion sort on A = [2, 2, 1]. How many shifts (A[i + 1] ← A[i]) happen in total?
Show answer
Two. At j = 2, A[1] > 2 is false, so nothing shifts. At j = 3 with key 1, both 2s shift right, and the array becomes [1, 2, 2].