Topic 7 · Algorithm design and problem-solving

Linear search and bubble sort

Video lesson: 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.

Example: search for 27 in [12, 45, 27, 8, 33]. Check 12 – no. Check 45 – no. Check 27 – found at position 3. The search stops.

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.

Example: sort [5, 3, 8, 1] into ascending order.
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

Exam tips

Want the full topic notes, slides and worksheets? See Notes & Slides, practise with the free CS with Aamir Quiz App, or order the O Level Computer Science Study Guide.