Question 1 Report
Study the following pseudocode that processes an array of integers.
DECLARE Nums : ARRAY[1:6] OF INTEGER
DECLARE Temp : INTEGER
DECLARE i : INTEGER
DECLARE Swapped : BOOLEAN
Nums[1] ← 8
Nums[2] ← 3
Nums[3] ← 5
Nums[4] ← 1
Nums[5] ← 9
Nums[6] ← 2
REPEAT
Swapped ← FALSE
FOR i ← 1 TO 5
IF Nums[i] > Nums[i + 1] THEN
Temp ← Nums[i]
Nums[i] ← Nums[i + 1]
Nums[i + 1] ← Temp
Swapped ← TRUE
ENDIF
NEXT i
UNTIL Swapped = FALSE(a) Complete the table to show the contents of the array after the first complete pass of the outer loop. [4]
| Nums[1] | Nums[2] | Nums[3] | Nums[4] | Nums[5] | Nums[6] |
|---|---|---|---|---|---|
(b) Name the sorting algorithm being used. [1]
(c) State the purpose of the variable Temp. [1]
(d) Explain why the variable Swapped is used. [2]
(e) State the minimum and maximum number of complete passes needed to sort an array of 6 elements using this algorithm. [2]
(a) The algorithm is a bubble sort. Starting with [8, 3, 5, 1, 9, 2], the inner FOR loop compares each adjacent pair from position 1 to 5:
| Comparison | Elements | Swap? | Array after |
|---|---|---|---|
| i=1: Nums[1] vs Nums[2] | 8 vs 3 | Yes | [3, 8, 5, 1, 9, 2] |
| i=2: Nums[2] vs Nums[3] | 8 vs 5 | Yes | [3, 5, 8, 1, 9, 2] |
| i=3: Nums[3] vs Nums[4] | 8 vs 1 | Yes | [3, 5, 1, 8, 9, 2] |
| i=4: Nums[4] vs Nums[5] | 8 vs 9 | No | [3, 5, 1, 8, 9, 2] |
| i=5: Nums[5] vs Nums[6] | 9 vs 2 | Yes | [3, 5, 1, 8, 2, 9] |
After the first complete pass, the array is: [3, 5, 1, 8, 2, 9]. The largest value (9) has "bubbled" to its correct final position. [4]
(b) The sorting algorithm is a bubble sort. It works by repeatedly comparing adjacent elements and swapping them if they are in the wrong order. [1]
(c) Temp is a temporary variable used to hold one value during the swap of two adjacent elements. Without it, one value would be overwritten and lost when the other is copied into its place. The three-step swap pattern (Temp <- A, A <- B, B <- Temp) preserves both values. [1]
(d) Swapped is a Boolean flag that tracks whether any swaps occurred during a complete pass through the array. [1] If no swaps were made during an entire pass (Swapped remains FALSE), the array is already sorted and the REPEAT loop terminates early. Without this flag, the algorithm would continue making unnecessary passes even after the array is fully sorted. [1] [2]
(e) Minimum: 1 pass. If the array is already sorted, one pass through the inner loop produces no swaps, so Swapped stays FALSE and the algorithm terminates after just that single pass. [1]
Maximum: 5 passes (n - 1 = 6 - 1 = 5). In the worst case (reverse-sorted array), each pass moves only one element to its correct position, requiring 5 passes to sort all 6 elements. [1] [2]
Everything you need to excel in your exams