Worked solution from the Data Types and Structures Paper 2 Problem-solving and Programming booklet, Part 2 of 4.
A bubble sort compares neighbouring rows and swaps them if they are in the wrong order. Here the comparison uses column 2 (the mark), but both columns must be swapped so each candidate number stays with its mark. A flag stops the sort early, and a boundary makes each pass shorter.
PROCEDURE Sort()
DECLARE Temp : INTEGER
DECLARE NoSwaps : BOOLEAN
DECLARE Boundary, Row, Col : INTEGER
Boundary ← 999
REPEAT
NoSwaps ← TRUE
FOR Row ← 1 TO Boundary
IF Result[Row, 2] > Result[Row + 1, 2] THEN
FOR Col ← 1 TO 2
Temp ← Result[Row, Col]
Result[Row, Col] ← Result[Row + 1, Col]
Result[Row + 1, Col] ← Temp
NEXT Col
NoSwaps ← FALSE
ENDIF
NEXT Row
Boundary ← Boundary - 1
UNTIL NoSwaps = TRUE
ENDPROCEDUREOuter loop (repeat passes) [1]
Inner loop through the rows [1]
Correct comparison of the marks (column 2) of neighbouring rows inside the loop [1]
Swap of the column 1 elements inside the loop [1]
Swap of the column 2 elements inside the loop (a loop or separate statements) [1]
NoSwaps flag set to TRUE at the start of each pass and the outer loop repeats until no swaps [1]
Flag set to FALSE inside the inner loop when a swap happens [1]
Boundary reduced by 1 in the outer loop [1]
▶ Whole paper
Video solution of the whole paper · by Papersdock. Tap the picture to open it on YouTube.
Solutions follow the official Cambridge mark schemes; marks are shown in grey. Videos are from other YouTube channels. Paper codes read component / series / year: M/J = May/June, O/N = October/November. Past-paper questions © UCLES, reproduced for classroom practice.