Paper 2: Pseudocode step by step (arrays, functions, procedures)

Paper 2: Pseudocode step by step (arrays, functions, procedures)

Arrays 4: swap, shift and bubble sort

1D arrays AS Level 19 min read

On this page
  1. What you need to be able to do
  2. Pattern 7a: swap two elements
  3. Pattern 7b: shift to delete or insert
  4. Pattern 8: bubble sort
  5. Worked example: a sorted list of names
  6. Practice: three levels
  7. Mistakes that lose marks
  8. Can I do this?

What you need to be able to do

Syllabus 10.2 Arrays, 9.2 Algorithms (Paper 2)
  • 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.

index12345
Data318521427
Swap Data[1] and Data[3]: afterwards 52 is at index 1 and 31 at index 3.
7aSwap with Temp

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

index12345
Data528311427
After the three lines.
Template
Temp ← Data[1]Data[1] ← Data[3]Data[3] ← Temp

Trap Writing Data[1] ← Data[3] then Data[3] ← Data[1] without Temp: both elements end up 52.

Trace table for the swap
TempData[1]Data[3]
313152
5231
Temp must have the same data type as the array elements. What type is Temp when swapping two names in a STRING array? STRING. (A common slip is DECLARE Temp : INTEGER for a STRING array.)

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

index1234567
Name"Ali""Bina""Cyrus""Dua""Eman"""""
Delete Bina (Pos = 2). Cyrus, Dua and Eman each move one place left; the last used element becomes "".
Delete the item at Pos
// 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

index1234567
Name"Ali""Bina""Cyrus""Dua""Eman"""""
Insert Chen at Pos = 3. Eman, Dua and Cyrus move right - starting from the END - then Chen goes into index 3.
Insert at Pos
// 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"
The direction of the loop matters. Shifting right with a loop that goes up copies Cyrus into index 4, then copies that same Cyrus into 5, then into 6: the array ends up "Ali", "Bina", "Cyrus", "Cyrus", "Cyrus", "Cyrus". To shift right, go down (STEP -1); to shift left, go up. Rule: start at the end the items are moving towards.
Before inserting, check there is a free element at the end (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

One pass over Data[1:5]
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
index12345
Data831521427
j = 1: 31 > 8? Yes - swap.
index12345
Data831521427
j = 2: 31 > 52? No - leave them.
index12345
Data831145227
j = 3: 52 > 14? Yes - swap.
index12345
Data831142752
j = 4: 52 > 27? Yes - swap.

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
jData[1]Data[2]Data[3]Data[4]Data[5]
1318521427
2831
31452
42752

The first row holds the starting values. A new row appears only when something changes.

The whole sort

8Bubble 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

index12345
Data814273152
Sorted after at most 4 passes.
Template
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 i

Trap 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 alphabeticallythe 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.

Bubble sort with a flag
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 = 0

On 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.

Why REPEAT and not WHILE? At least one pass is always needed to find out whether the array is sorted. (A WHILE version works too, if NoSwaps is set to FALSE before the loop.)

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.

ModuleDescription
InsertName()
  • called with a name
  • the global array Name[1:100] holds names in alphabetical order, used elements first, unused elements contain an empty string
  • if the array is full, returns FALSE
  • otherwise inserts the name in the correct place, keeping the order, and returns TRUE
Example 1 · InsertName() (own example) ★★★ Hard
Q1Practice8 marks

Write pseudocode for the function InsertName() described in the table above.

1 Read it with me what is actually happening?

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)
2 What is it asking for? the target, part by part
  • 1Full?check before changing anything
  • 2Lastthe last used element
  • 3Poswhere the new name belongs
  • 4Shift and insertmove Last … Pos one right, put the name at Pos
3 What do we know? everything the question gives us
  • 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.
4 Plan the route work backwards from what we want
FindKey ideaAlready have itWork out firstTrap
  • 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
  1. If Name[100] <> "" RETURN FALSE.
  2. Last ← 0; WHILE the next element is used, Last ← Last + 1.
  3. Pos ← 1; WHILE Pos <= Last AND Name[Pos] < NewName, Pos ← Pos + 1.
  4. FOR i ← Last TO Pos STEP -1: Name[i + 1] ← Name[i].
  5. Name[Pos] ← NewName; RETURN TRUE.
Model answer
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 TRUEENDFUNCTION
6 Check it does the answer make sense?

Tested: 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] ← Temp

L1.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 Swaps

12, 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 i

Swap 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 i

Only 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] ← ""   ENDIFENDPROCEDURE

Search 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 Passes

12, 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] ← KeepENDPROCEDURE

The 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

MistakeWrite 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 arrayTemp 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 upShift right going down (STEP -1); shift left going up
Forgetting the old last element after a deleteSet it to the unused value ("" / -1)
“Stops when sorted” with no flag in the codeNoSwaps ← TRUE at the start of each pass, FALSE on any swap, REPEAT … UNTIL NoSwaps

Can I do this?

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