9618/21/M/J/21 question 5: worked solution (May/June 2021, paper 21)

Show as plain text

Cambridge AS Level Computer Science 9618 · 10.2 Arrays Worked solution from the Data Types and Structures Paper 2 Problem-solving and Programming booklet, Part 2 of 4. Q9 9618/21/M/J/21 original Q5 Structured · 8 marks Worked solution 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 ENDPROCEDURE Outer 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] KEY IDEA An efficient bubble sort stops when a pass makes no swaps and checks one fewer row each pass; swap whole rows, not just the marks. TOTAL 8 marks Official mark scheme VIDEO ▶ Whole paper Video solution of the whole paper · by Papersdock. Tap the picture to open it on YouTube.