Track progress, take quizzes and save notes on this lesson.

Free forever · no card needed

Start free
Intermediate

Bubble Sort

3.1.4 Sorting algorithms

Aligned to the AQA 8525 specification

Level
Intermediate
Reading time
6 min
Published
6 June 2026
Updated
1 July 2026
On this page
  1. 1.How Bubble Sort Works
  2. 2.First Pass: A Worked Example
  3. 3.Completing the Sort
  4. 4.The Swap Flag Optimisation
  5. 5.Time Complexity: Why O(n²)?
  6. 6.Bubble Sort vs Merge Sort
  7. 7.Common Exam Mistakes

Key takeaways

  • Bubble sort compares adjacent pairs and swaps them if they are in the wrong order, repeating across passes until no more swaps are needed.
  • After k passes the k largest elements are in their correct positions at the end of the list; after just one pass only the largest element is guaranteed to be in place.
  • For a list of n elements, at most n - 1 passes are needed, and each pass can shorten its comparison range by one since the last elements are already sorted.
  • The swap flag optimisation sets a flag to False at the start of each pass and to True on any swap, exiting early if no swap occurs, giving a best case of O(n).
  • Bubble sort's worst-case time complexity is O(n^2) because total comparisons equal n(n-1)/2, so doubling the list size quadruples the comparisons.

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.

The Swap Flag Optimisation

Without any optimisation, bubble sort always runs exactly passes — even on a list that is already sorted.

The swap flag fixes this. At the start of each pass, set a flag to False. If any swap occurs during that pass, set it to True. At the end of the pass:

  • If the flag is still False → no swaps occurred → the list is already sorted → exit early
  • If the flag is True → at least one swap occurred → run another pass
swapped ← True
endIndex ← n - 2
WHILE swapped = True
    swapped ← False
    FOR i ← 0 TO endIndex
        IF list[i] > list[i + 1] THEN
            swap(list[i], list[i + 1])
            swapped ← True
        END IF
    END FOR
    endIndex ← endIndex - 1
END WHILE

Example on an already-sorted list [1, 2, 3, 4, 5]:

Pass 1: 1 < 2 (no swap), 2 < 3 (no swap), 3 < 4 (no swap), 4 < 5 (no swap). Flag stays False → exit.

Only 1 pass and 4 comparisons are needed — not 4 passes and 10 comparisons. This makes the optimised best case O(n).

Something not quite clicking?

Ask Aica to explain any part of this differently. Free, takes 30 seconds.

Ask Aica

Time Complexity: Why O(n²)?

The number of comparisons in the worst case follows a predictable pattern. Each pass compares one fewer pair than the last:

PassComparisons made
1
2
3
1

Total comparisons =

For small this is manageable. For large it becomes impractical:

Maximum comparisons
510
1045
1004,950
1,000499,500
10,000~50,000,000

Since , the complexity is written as — doubling the list size quadruples the number of comparisons.

Best case (optimised, already-sorted list): — one pass, no swaps detected. Worst case (reverse-sorted list): .

Bubble Sort vs Merge Sort

Both algorithms sort a list, but they differ significantly in performance and memory use.

PropertyBubble sortMerge sort
Worst-case complexity
Best-case complexity (optimised, with flag)
Extra memory requiredNone — sorts in placeYes — sub-lists during merge
For up to 4,950 comparisons~664 comparisons
For up to ~50,000,000 comparisons~133,000 comparisons

When bubble sort is preferred:

  • The list is very small — the overhead difference is negligible
  • The list is nearly sorted — the swap flag exits after very few passes
  • Memory is severely constrained — merge sort needs additional space proportional to

For large unsorted datasets, merge sort is generally the better choice. The gap widens rapidly as grows.

Common Exam Mistakes

1. Stopping after one pass

Bubble sort requires multiple passes. After one pass, only the largest element is guaranteed to be in its final position. The remaining elements may still be out of order.

2. Confusing the direction of bubbling

Each pass moves the largest unsorted element to the right (the end). Elements do not bubble to the left. If you are sorting in ascending order, the sorted region grows at the right end of the list.

3. Not reducing the comparison range each pass

After pass , the last elements are sorted and need not be compared again. The inner loop shortens by one each pass. Comparing already-sorted elements wastes steps and can cost marks in a trace question.

4. Forgetting to describe the swap flag when asked about the optimised version

The optimisation is not just "stop when sorted" — the mechanism is a boolean flag set to False at the start of each pass and updated to True on any swap. If the flag remains False at the end of a pass, the algorithm terminates. Describing it vaguely as "it stops early" is not sufficient.

5. Claiming bubble sort always uses less memory than merge sort

Bubble sort is in-place and uses constant extra memory, which is an advantage. But this does not mean bubble sort is generally better — merge sort's performance far outweighs its memory cost for any large dataset.

Frequently asked questions

In the worst case each pass makes one fewer comparison than the last, so the total is (n-1) + (n-2) + ... + 1 = n(n-1)/2. Since this is approximately n^2/2, the complexity is written O(n^2), meaning doubling the list size roughly quadruples the number of comparisons.

It lets bubble sort exit early once the list is sorted. A flag is set to False at the start of each pass and to True if any swap occurs. If the flag is still False at the end of a pass, no swaps happened, the list is sorted and the algorithm stops, giving a best case of O(n).

Bubble sort is preferred when the list is very small, when it is nearly sorted so the swap flag exits after few passes, or when memory is severely constrained, since it sorts in place using no extra memory while merge sort needs additional space proportional to n. For large unsorted datasets merge sort is generally better.

Generate revision on any topic you study

Type any topic you're studying and Aicademy generates a complete lesson, quiz, and flashcard set, personalised to your level.

Lessons on anything

Structured, level-matched lessons on any topic you study

Practice quizzes

Find out what you actually know before the exam does

Flashcard sets

Lock in key concepts with instant revision cards

Ask Aica

Stuck on something? Get a clear explanation, any time

Prev

Linear Search and Binary Search

Next

Merge Sort

Top students don’t revise more. They revise what counts.

Start revising free

Free to start. No card needed.