Linear search and bubble sort
▶ Watch the video lessonShort, exam-focused explanation of this topic on the CS with Aamir YouTube channel.Searching and sorting are two of the standard methods you must know for Paper 2. You need to be able to describe how they work, trace them with data, and write them in pseudocode.
Linear search
A linear search checks each item in a list one at a time, starting from the first, until it finds the value it is looking for or reaches the end of the list.
This pseudocode searches an array Numbers of 10 items for SearchValue:
Found ← FALSE
Index ← 1
WHILE Found = FALSE AND Index <= 10 DO
IF Numbers[Index] = SearchValue
THEN
Found ← TRUE
ELSE
Index ← Index + 1
ENDIF
ENDWHILE
IF Found = TRUE
THEN
OUTPUT "Found at position ", Index
ELSE
OUTPUT "Not found"
ENDIF
Linear search works on any list, sorted or unsorted, but it can be slow for long lists because in the worst case every item has to be checked.
Bubble sort
A bubble sort puts a list into order by repeatedly comparing each pair of neighbouring items and swapping them if they are in the wrong order. After each complete pass, the largest remaining value has "bubbled" to the end. The sort stops when a pass makes no swaps.
Pass 1: 5 > 3 swap → [3, 5, 8, 1]; 5 < 8 no swap; 8 > 1 swap → [3, 5, 1, 8]
Pass 2: 3 < 5 no swap; 5 > 1 swap → [3, 1, 5, 8]
Pass 3: 3 > 1 swap → [1, 3, 5, 8] – the list is sorted.
This pseudocode sorts an array Numbers of 10 items into ascending order. For a different-sized array, change the starting value of Last and the 10 in the linear search.
Last ← 10
REPEAT
Swapped ← FALSE
FOR Index ← 1 TO Last - 1
IF Numbers[Index] > Numbers[Index + 1]
THEN
Temp ← Numbers[Index]
Numbers[Index] ← Numbers[Index + 1]
Numbers[Index + 1] ← Temp
Swapped ← TRUE
ENDIF
NEXT Index
Last ← Last - 1
UNTIL (NOT Swapped) OR Last <= 1
Key points about the bubble sort code
- A temporary variable (Temp) is needed to swap two values – without it one value would be overwritten and lost.
- The Swapped flag lets the algorithm stop early when the list is already in order.
- Reducing Last by 1 after each pass avoids checking the end of the list, which is already sorted.
- To sort into descending order, change > to < in the comparison.
Exam tips
- When tracing, write out the whole list after every pass – examiners award marks for each correct pass.
- Use the exact Cambridge pseudocode keywords: ← for assignment, ENDIF, ENDWHILE, NEXT, UNTIL.
- For "describe" questions, explain the comparing, swapping and repeating, and say when the algorithm stops.