Sorting: Bubble & Selection
Learning objective
By the end of this lesson you will be able to implement bubble and selection sort and compare their complexity.
Sorted data makes searching, merging and reporting easier — and enables fast algorithms like binary search.
Bubble sort
Repeatedly compare neighbouring items and swap them if they are out of order. The largest value bubbles to the end on each pass.
def bubble_sort(items):
n = len(items)
for i in range(n):
for j in range(n - 1 - i):
if items[j] > items[j + 1]:
items[j], items[j + 1] = items[j + 1], items[j]
return items
print(bubble_sort([5, 2, 9, 1])) # [1, 2, 5, 9]Selection sort
Find the smallest remaining item and swap it into place, one position at a time.
def selection_sort(items):
for i in range(len(items)):
small = i
for j in range(i + 1, len(items)):
if items[j] < items[small]:
small = j
items[i], items[small] = items[small], items[i]
return items
print(selection_sort([5, 2, 9, 1])) # [1, 2, 5, 9]Complexity
- Both run in O(n²) worst case — fine for small lists
- Larger datasets use faster sorts such as merge sort (O(n log n))
- Simple sorts are easy to write and debug
Code playground
Run and edit the starter code — experiment freely.
Output appears here when you press Run.
Practice exercise
Trace bubble sort on [4, 1, 3, 2] — write the list after each full pass.
Check your understanding
1. What is the worst-case complexity of bubble sort?
2. Which sort repeatedly finds the smallest item and places it?
Self-graded — answer then check below.