Paper 2: Pseudocode step by step (arrays, functions, procedures)
Arrays 4: swap, shift and bubble sort
What you need to be able to do
- 10.2Swap two elements of an array using a temporary variable.
- 10.2Shift elements left to delete an item, or right to make room for a new one, keeping the order.
- 9.2Write a bubble sort (ascending or descending, numbers or strings), and the improved version that stops when a pass makes no swaps.
- 9.2Describe a bubble sort in words, for the questions that ask for a description, not code.
You need: Arrays 3 (search and unused elements) and nested loops.
Pattern 7a: swap two elements
A variable holds one value. If you copy Data[1] into Data[2] first, the old Data[2] is gone for ever. So a swap needs a third variable, Temp, to keep one value safe while the other is moved. Think of swapping the drinks in two full glasses: you need an empty third glass.
| index | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| Data | 31 | 8 | 52 | 14 | 27 |
Save one value in Temp, copy the other across, then put Temp into the second place. Three lines, always in a circle: Temp ← A, A ← B, B ← Temp.
Use it when the question says swap, exchange, change the order of, reverse
| index | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| Data | 52 | 8 | 31 | 14 | 27 |
Temp ← Data[1]Data[1] ← Data[3]Data[3] ← TempTrap Writing Data[1] ← Data[3] then Data[3] ← Data[1] without Temp: both elements end up 52.
| Temp | Data[1] | Data[3] |
|---|---|---|
| 31 | 31 | 52 |
| 52 | 31 |
Pattern 7b: shift to delete or insert
When the order of the items matters (a queue of names, a sorted list), you can't just put "" in the middle. Deleting an item means moving everything after it one place to the left to close the gap. Inserting means moving items one place to the right to open a gap. The used items stay together at the front, and the unused elements stay at the end.
Delete: shift left
| index | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| Name | "Ali" | "Bina" | "Cyrus" | "Dua" | "Eman" | "" | "" |
// Pos = the element to delete, Last = the last used elementFOR i ← Pos TO Last - 1 Name[i] ← Name[i + 1]NEXT iName[Last] ← ""Insert: shift right
| index | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| Name | "Ali" | "Bina" | "Cyrus" | "Dua" | "Eman" | "" | "" |
// open a gap at Pos, then fill it (the array must have a free element at the end)FOR i ← Last TO Pos STEP -1 Name[i + 1] ← Name[i]NEXT iName[Pos] ← "Chen"Name[Upper] = ""). If not, the array is full - the question usually wants a FALSE or an error message then.Pattern 8: bubble sort
A bubble sort puts an array in order by comparing neighbouring elements (j and j + 1) and swapping them when they are the wrong way round. One trip from the start to the end is a pass. After the first pass the biggest value has “bubbled” to the last element; after the second pass the second biggest is in place, and so on.
One pass, step by step
FOR j ← 1 TO 4 IF Data[j] > Data[j + 1] THEN Temp ← Data[j] Data[j] ← Data[j + 1] Data[j + 1] ← Temp ENDIFNEXT j| index | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| Data | 8 | 31 | 52 | 14 | 27 |
| index | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| Data | 8 | 31 | 52 | 14 | 27 |
| index | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| Data | 8 | 31 | 14 | 52 | 27 |
| index | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| Data | 8 | 31 | 14 | 27 | 52 |
After one pass 52, the largest, is in its final place. The rest are still not sorted, so we need more passes.
See the trace table for one pass
| j | Data[1] | Data[2] | Data[3] | Data[4] | Data[5] |
|---|---|---|---|---|---|
| 1 | 31 | 8 | 52 | 14 | 27 |
| 2 | 8 | 31 | |||
| 3 | 14 | 52 | |||
| 4 | 27 | 52 |
The first row holds the starting values. A new row appears only when something changes.
The whole sort
An outer loop for the passes (n - 1 of them for n elements), an inner loop comparing neighbours j and j + 1. Each pass can stop one element earlier, because the end of the array is already sorted.
Use it when the question says sort, put in ascending / descending / alphabetical order, bubble sort
| index | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| Data | 8 | 14 | 27 | 31 | 52 |
FOR i ← 1 TO 4 FOR j ← 1 TO 5 - i IF Data[j] > Data[j + 1] THEN Temp ← Data[j] Data[j] ← Data[j + 1] Data[j + 1] ← Temp ENDIF NEXT jNEXT iTrap The inner loop must stop at upper bound - 1 (or 5 - i): it reads Data[j + 1]. FOR j ← 1 TO 5 reads Data[6], which doesn't exist - a run-time error.
| To sort … | Change |
|---|---|
| ascending (smallest first) | IF Data[j] > Data[j + 1] THEN |
| descending (largest first) | IF Data[j] < Data[j + 1] THEN |
| names alphabetically | the same >: strings compare letter by letter ("Ali" < "Bina"). Temp must be a STRING. |
The improved version: stop when nothing moves
If a pass makes no swaps, the array is already sorted and the rest of the passes are wasted. The improved bubble sort keeps a BOOLEAN flag (NoSwaps) and repeats passes until a pass made no swaps.
Boundary ← 4REPEAT NoSwaps ← TRUE FOR j ← 1 TO Boundary IF Data[j] > Data[j + 1] THEN Temp ← Data[j] Data[j] ← Data[j + 1] Data[j + 1] ← Temp NoSwaps ← FALSE ENDIF NEXT j Boundary ← Boundary - 1UNTIL NoSwaps = TRUE OR Boundary = 0On an array that is already almost sorted, such as 1, 2, 3, 5, 4, this version stops after 2 passes instead of 4: the first pass swaps 5 and 4, the second pass finds nothing to swap.
Describe it in words
Some questions say “Describe how a bubble sort works” or “Explain how the algorithm could be made more efficient”. The marks go to these points - each one is a short sentence:
• Compare each element with the next one (neighbouring elements / pairs).
• If they are in the wrong order, swap them.
• Repeat for every pair from the start to the end of the array: this is one pass.
• After each pass the largest remaining value is in its correct place at the end.
• Repeat the passes until a pass makes no swaps (or n - 1 passes have been made).
• More efficient: use a flag so the sort stops as soon as a pass makes no swaps, and reduce the number of comparisons by one after each pass.
Worked example: a sorted list of names
Keeping an array in order as items arrive uses search + shift together - no sort needed afterwards.
| Module | Description |
|---|---|
InsertName() |
|
Example 1 · InsertName() (own example) ★★★ Hard
Write pseudocode for the function InsertName() described in the table above.
The list is already in order. A new name must go just before the first name that comes after it in the alphabet. Everything from there to the last used element moves one place right to make room.
- alphabetical orderthe names are already sorted: we never need a full sort
- used elements firstthe used names are together at the front, so one Last index marks the end
- if the array is fullName[100] is in use: there is nowhere to shift to
- keeping the orderfind the place, shift right, insert (pattern 7b)
- 1Full?
- 2Last
- 3Pos
- 4Shift and insert
- 100elements
- ""marks an unused element
- Strings compare alphabetically with < and >, so Name[Pos] < NewName means “still before it”.
- If the array is empty, Last = 0 and Pos = 1: the shift loop runs zero times.
- FindInsertName(NewName)
- Work out firstLast: count the used elements
- Work out nextPos: move on while Name[Pos] < NewName
- Trapshift right DOWNWARDS (STEP -1), or one name is copied all the way along
Why check Name[100] rather than counting first?
If the last element is used, the array is full - one test is enough.
Where does a name go that comes after every other name?
Pos stops at Last + 1, the first unused element; nothing is shifted.
5 Now solve it have a go on paper first, then open the worked solution
- If Name[100] <> "" RETURN FALSE.
- Last ← 0; WHILE the next element is used, Last ← Last + 1.
- Pos ← 1; WHILE Pos <= Last AND Name[Pos] < NewName, Pos ← Pos + 1.
- FOR i ← Last TO Pos STEP -1: Name[i + 1] ← Name[i].
- Name[Pos] ← NewName; RETURN TRUE.
FUNCTION InsertName(NewName : STRING) RETURNS BOOLEAN DECLARE i, Pos, Last : INTEGER IF Name[100] <> "" THEN RETURN FALSE ENDIF Last ← 0 WHILE Last < 100 AND Name[Last + 1] <> "" Last ← Last + 1 ENDWHILE Pos ← 1 WHILE Pos <= Last AND Name[Pos] < NewName Pos ← Pos + 1 ENDWHILE FOR i ← Last TO Pos STEP -1 Name[i + 1] ← Name[i] NEXT i Name[Pos] ← NewName RETURN TRUEENDFUNCTIONTested: Ali, Bina, Dua + Chen, Aaron, Zoya gives Aaron, Ali, Bina, Chen, Dua, Zoya; an empty array takes Ali at index 1; a full array returns FALSE.
Practice: three levels
L1 Basic
One swap, one pass, one shift.
L1.1 First and last
Score : ARRAY[1:6] OF INTEGER is full. Swap the first and last elements.
Show the model answer
Temp ← Score[1]Score[1] ← Score[6]Score[6] ← TempL1.2 Count the swaps
Do one bubble-sort pass over Score (ascending) and output how many swaps it made.
Show the model answer
DECLARE Swaps : INTEGERSwaps ← 0FOR j ← 1 TO 5 IF Score[j] > Score[j + 1] THEN Temp ← Score[j] Score[j] ← Score[j + 1] Score[j + 1] ← Temp Swaps ← Swaps + 1 ENDIFNEXT jOUTPUT Swaps12, 40, 7, 25, 3, 18: 40 swaps with 7, then 25, then 3, then 18 - four swaps, and 40 ends at index 6.
L1.3 Delete the first
Queue : ARRAY[1:5] OF STRING holds names, used elements first and "" after. Remove the name at index 1 by shifting the rest left, and make the last element "".
Show the model answer
FOR i ← 1 TO 4 Queue[i] ← Queue[i + 1]NEXT iQueue[5] ← ""Shifting left goes up. Copying an empty string over an empty string is harmless, so the loop can simply run to 4.
L2 Medium
Reverse, sort the other way, search then shift.
L2.1 Reverse
Reverse the order of the elements of Score (6 elements) in place - no second array.
Hint
Which element does Score[1] swap with? Score[2]? Find a formula.
Show the model answer
FOR i ← 1 TO 3 Temp ← Score[i] Score[i] ← Score[7 - i] Score[7 - i] ← TempNEXT iSwap 1 with 6, 2 with 5, 3 with 4. Only go halfway: going to 6 swaps everything back again.
L2.2 Highest first
Sort Score into descending order with a bubble sort.
Show the model answer
FOR i ← 1 TO 5 FOR j ← 1 TO 6 - i IF Score[j] < Score[j + 1] THEN Temp ← Score[j] Score[j] ← Score[j + 1] Score[j + 1] ← Temp ENDIF NEXT jNEXT iOnly the comparison changes: swap when the left one is SMALLER.
L2.3 Delete by name
Write a procedure Leave() that takes a name and removes it from the global array Queue : ARRAY[1:5] OF STRING (used elements first, "" after), keeping the order of the others. If the name is not there, output Not in queue.
Show the model answer
PROCEDURE Leave(Who : STRING) DECLARE i, Pos : INTEGER Pos ← 0 FOR i ← 1 TO 5 IF Queue[i] = Who AND Pos = 0 THEN Pos ← i ENDIF NEXT i IF Pos = 0 THEN OUTPUT "Not in queue" ELSE FOR i ← Pos TO 4 Queue[i] ← Queue[i + 1] NEXT i Queue[5] ← "" ENDIFENDPROCEDURESearch first (pattern 4, here with Pos = 0 meaning “not found yet”), then shift left from Pos.
L3 Hard
Change the swap rule, count passes, keep a value while shifting.
L3.1 Sort names, gaps last
Name : ARRAY[1:8] OF STRING holds names in any order with unused elements ("") anywhere. Sort it so the names are in alphabetical order at the front and all the "" are at the end.
Hint
Plain > puts "" before "Ali". What should happen when Name[j] is empty?
Show the model answer
DECLARE i, j : INTEGERDECLARE Temp : STRINGFOR i ← 1 TO 7 FOR j ← 1 TO 8 - i IF Name[j] = "" OR (Name[j + 1] <> "" AND Name[j] > Name[j + 1]) THEN Temp ← Name[j] Name[j] ← Name[j + 1] Name[j + 1] ← Temp ENDIF NEXT jNEXT i"" would sort FIRST with a plain >, so change the rule for when to swap: an empty left element always moves right; otherwise swap only two real names in the wrong order. (Swapping two "" is harmless.)
L3.2 Count the passes
Use the improved bubble sort (with a flag) to sort Score ascending, and output how many passes it made, including the last pass that made no swaps.
Show the model answer
DECLARE Passes, Boundary : INTEGERDECLARE NoSwaps : BOOLEANPasses ← 0Boundary ← 5REPEAT NoSwaps ← TRUE FOR j ← 1 TO Boundary IF Score[j] > Score[j + 1] THEN Temp ← Score[j] Score[j] ← Score[j + 1] Score[j + 1] ← Temp NoSwaps ← FALSE ENDIF NEXT j Passes ← Passes + 1 Boundary ← Boundary - 1UNTIL NoSwaps = TRUE OR Boundary = 0OUTPUT Passes12, 40, 7, 25, 3, 18 needs 5 passes; an already sorted array needs only 1.
L3.3 Move to the front
Write a procedure ToFront() that takes an index n (1 to 6) and moves Score[n] to index 1. The elements that were before it each move one place right; the rest don't move. (E.g. n = 4 on 12, 40, 7, 25, 3, 18 gives 25, 12, 40, 7, 3, 18.)
Show the model answer
PROCEDURE ToFront(n : INTEGER) DECLARE i, Keep : INTEGER Keep ← Score[n] FOR i ← n - 1 TO 1 STEP -1 Score[i + 1] ← Score[i] NEXT i Score[1] ← KeepENDPROCEDUREThe value at n would be overwritten by the shift, so keep it first (the same job Temp does in a swap). Shift right = go down.
Mistakes that lose marks
| Mistake | Write this instead |
|---|---|
Swapping without Temp (A[j] ← A[j + 1] then A[j + 1] ← A[j]) | Temp ← A[j], A[j] ← A[j + 1], A[j + 1] ← Temp |
| Temp declared as INTEGER for a STRING array | Temp has the element type |
Inner loop FOR j ← 1 TO 10 on ARRAY[1:10] | FOR j ← 1 TO 9 (or 10 - i): it reads A[j + 1] |
| Shifting right with a loop that goes up | Shift right going down (STEP -1); shift left going up |
| Forgetting the old last element after a delete | Set it to the unused value ("" / -1) |
| “Stops when sorted” with no flag in the code | NoSwaps ← TRUE at the start of each pass, FALSE on any swap, REPEAT … UNTIL NoSwaps |
Can I do this?
- I can swap two elements with a temporary variable.
- I can shift left to delete and right to insert, with the loop going the right way.
- I can write a bubble sort (either order, numbers or names) and the version with a flag.
- I can describe a bubble sort in words, including how to make it more efficient.
Anything unticked: revise that section first. All ticked: take the quiz.
The multiple-choice and guided questions need JavaScript. The concept checks and exam practice below work without it.
Concept checks
Answer each one in your head first, then open it.
1Why does an ascending bubble sort need at most n - 1 passes for n elements?Show answer
Each pass puts one more value in its final place at the end; when n - 1 are placed, the last one must be in place too.
2Why can each pass compare one pair fewer than the one before?Show answer
The last element(s) already hold the largest values in order, so comparing them again can never cause a swap.
3Why does shifting right have to start from the end?Show answer
Each element is copied into the place after it before that place's own value is moved on; starting from the front would overwrite values that haven't been moved yet.
Your progress on this note is saved when JavaScript is on.
⬇️ Download this chapter as a PDF: Full notes · Worksheets · Answers