Intermediate

Bubble Sort

AicademyAicademy
·GCSE Computer Science·AQA 8525·7 slides
3.1.4 Sorting algorithms

How Bubble Sort Works

Bubble sort compares adjacent pairs of elements and swaps them if they are in the wrong order. It repeats this process across multiple passes through the list until no more swaps are needed and the list is fully sorted.

The name comes from the effect each pass has: the largest unsorted element gradually "bubbles up" to its correct position at the end of the list.

After each pass, the next-largest unsorted element settles into its final position. After k passes, the k largest elements are in their correct positions at the end.

Rules for each comparison:

  • Compare the element at position with the element at position
  • If they are in the wrong order (left > right), swap them
  • Move on to the next pair
  • Repeat until the end of the unsorted region

For a list of elements, at most passes are needed.

First Pass: A Worked Example

Sort [5, 3, 8, 1, 4] using bubble sort.

Starting with the full list, pass 1 makes comparisons:

StepComparisonSwap?List after step
15 vs 3Yes[3, 5, 8, 1, 4]
25 vs 8No[3, 5, 8, 1, 4]
38 vs 1Yes[3, 5, 1, 8, 4]
48 vs 4Yes[3, 5, 1, 4, 8]

After pass 1: [3, 5, 1, 4, 8]

The value 8 — the largest element — has reached its final position at the end. It will not be compared again in future passes.

Write carries and swaps explicitly in exams. Do not attempt to track multiple swaps mentally.

Completing the Sort

Continuing with [3, 5, 1, 4, 8]. Each pass shortens the unsorted region by one element.

Pass 2 (3 comparisons — position 4 is already sorted):

StepComparisonSwap?List after step
13 vs 5No[3, 5, 1, 4, 8]
25 vs 1Yes[3, 1, 5, 4, 8]
35 vs 4Yes[3, 1, 4, 5, 8]

Remaining passes (summary):

After passList stateSorted region
1[3, 5, 1, 4, 8]last 1 element
2[3, 1, 4, 5, 8]last 2 elements
3[1, 3, 4, 5, 8]last 3 elements
4[1, 3, 4, 5, 8]fully sorted

Pass 3 details: compare 3 vs 1 (swap → [1, 3, 4, 5, 8]), compare 3 vs 4 (no swap). Pass 4: compare 1 vs 3 (no swap). List is now sorted.

4 more slides

Continue this lesson

Create a free account to unlock all 7 slides, track your progress, and ask the AI tutor for help.

Related lessons

7 Slides

Lesson

Merge Sort

GCSE Computer Science · AQA 8525

3 days ago

7 Slides

Lesson

Linear Search and Binary Search

GCSE Computer Science · AQA 8525

3 days ago