Home›Study Resources›Computer Science›
How does a bubble sort work?
Computer Science
GCSE

How does a bubble sort work?

A bubble sort compares each pair of neighbouring items and swaps them if they are in the wrong order. After each pass, the largest unsorted item reaches the end of the list. The algorithm stops when a full pass makes no swaps. Example: Sort 5, 3, 8, 1 into ascending order using a bubble sort. Pass 1: 5, 3 swap; 5, 8 stay; 8, 1 swap. List: 3, 5, 1, 8 Pass 2: 3, 5 stay; 5, 1 swap; 5, 8 stay. List: 3, 1, 5, 8 Pass 3: 3, 1 swap; others stay. List: 1, 3, 5, 8 Pass 4: no swaps, so the list is sorted. Answer: 1, 3, 5, 8

A bubble sort compares each pair of neighbouring items and swaps them if they are in the wrong order. After each pass, the largest unsorted item reaches the end of the list. The algorithm stops when a full pass makes no swaps.

Worked example

Sort 5, 3, 8, 1 into ascending order using a bubble sort.

  1. Pass 1: 5, 3 swap; 5, 8 stay; 8, 1 swap. List: 3, 5, 1, 8
  2. Pass 2: 3, 5 stay; 5, 1 swap; 5, 8 stay. List: 3, 1, 5, 8
  3. Pass 3: 3, 1 swap; others stay. List: 1, 3, 5, 8
  4. Pass 4: no swaps, so the list is sorted.

Answer: 1, 3, 5, 8

Reviewed by

Want one-to-one support?

One-to-one online tuition can help you build confidence in your subject. Find a tutor who teaches your course.

Find a Tutor

Learn face to face in Glasgow

Prefer in-person lessons? Visit the ExpertTutor Glasgow Southside centre.

See the centre