Skip to content

Module 18 · Algorithms and Problem Solving — topic 10 of 18

Bubble sort

The simplest sorting algorithm: repeatedly swapping adjacent elements that are out of order, tracing passes, the early-exit optimisation, counting comparisons, stability and O(n²) cost.

Beginner 8 min read·Lesson 270 of 306 in Python Programming

Learning objectives

  • Implement bubble sort with early exit
  • Trace the list after each pass
  • Analyse its comparisons and complexity

Definition

Bubble sort repeatedly steps through a list, compares each pair of adjacent elements and swaps them if they are in the wrong order. After each pass, the largest remaining element 'bubbles' to its final position at the end.

Introduction

Bubble sort is rarely used in real programs, but it is the clearest introduction to how sorting algorithms compare and move data.

Why it matters

Understanding why bubble sort is slow builds intuition for the faster algorithms — and for reasoning about any nested loop.

Detailed explanation

One pass compares a[0] with a[1], a[1] with a[2], and so on, swapping pairs that are out of order.

After pass i, the last i elements are in their final positions, so each pass can stop one element earlier.

If a pass makes no swaps, the list is sorted and the algorithm can stop early. This makes the best case (already sorted data) O(n).

In the worst case (reverse order), it performs n(n − 1)/2 comparisons: O(n²).

Bubble sort is stable: equal elements keep their original order because only strictly greater neighbours are swapped.

It sorts in place, using O(1) extra memory.

In Python, swap with tuple assignment: a[j], a[j + 1] = a[j + 1], a[j].

For real work, use sorted() or list.sort(), which use the much faster Timsort.

Syntax

Python
def bubble_sort(items):
a = list(items)
for i in range(len(a) - 1):
swapped = False
for j in range(len(a) - 1 - i):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
swapped = True
if not swapped:
break
return a
  • Swap adjacent pairs.
  • Each pass fixes the largest remaining item.
  • Stop early when no swaps happen.

Code examples

Bubble sort

Python
def bubble_sort(items):
a = list(items)
n = len(a)
for i in range(n - 1):
swapped = False
for j in range(n - 1 - i):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
swapped = True
if not swapped:
break
return a
print(bubble_sort([5, 1, 4, 2, 8]))
Output
[1, 2, 4, 5, 8]

Watching each pass

Python
def bubble_trace(items):
a = list(items)
for i in range(len(a) - 1):
for j in range(len(a) - 1 - i):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
print(f"pass {i + 1}: {a}")
bubble_trace([5, 1, 4, 2, 8])
Output
pass 1: [1, 4, 2, 5, 8]
pass 2: [1, 2, 4, 5, 8]
pass 3: [1, 2, 4, 5, 8]
pass 4: [1, 2, 4, 5, 8]

More examples

Counting comparisons

Python
def bubble_count(items):
a = list(items)
comparisons = 0
for i in range(len(a) - 1):
swapped = False
for j in range(len(a) - 1 - i):
comparisons += 1
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
swapped = True
if not swapped:
break
return comparisons
print(bubble_count(range(10)), bubble_count(range(10, 0, -1)), bubble_count([1, 2, 3, 5, 4]))
Output
9 45 7

Step-by-step explanation

  • Already sorted data needs one pass of 9 comparisons before the early exit.
  • Reversed data needs every pass: 9 + 8 + … + 1 = 45 comparisons.
  • A nearly sorted list is fixed in the first pass and confirmed in the second, using 7 comparisons.

Expected output

Running “Counting comparisons” prints exactly:

TextOutput
9 45 7

Practical applications

  • Teaching and visualising sorting.
  • Tiny lists where simplicity matters more than speed.

Best practices

  • Use the early-exit flag.
  • Copy the input if callers expect it unchanged.
  • Use sorted() in real code.

Common mistakes

Comparing past the end

Avoid

for j in range(len(a)):
if a[j] > a[j + 1]: # IndexError

Prefer

for j in range(len(a) - 1 - i):

The last element has no right-hand neighbour.

Important notes

  • Visualisation sites show bubble sort's slow 'bubbling' clearly — worth watching once.

Key takeaways

  • Bubble sort swaps adjacent out-of-order pairs.
  • O(n²) worst case, O(n) best case with early exit.
  • Stable and in place.

Try it yourself

  1. 1
    Modify bubble sort to sort in descending order.
  2. 2
    Sort a list of (name, marks) tuples by marks with bubble sort and check that it is stable.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
Practise this topic