Swap your way to understanding.
Trace a simple quadratic algorithm and understand why built-ins are the practical default.
01 The idea
Bubble sort repeatedly compares neighbours and swaps out-of-order pairs. It is easy to trace but usually inefficient for large inputs, with quadratic worst-case comparisons. An early-exit flag stops a pass sequence when no swap occurs. Study it to understand invariants and complexity; use Python’s built-in sorting for most real application work.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
def bubble_sort(values):
result = list(values)
for end in range(len(result) - 1, 0, -1):
changed = False
for index in range(end):
if result[index] > result[index + 1]:
result[index], result[index + 1] = result[index + 1], result[index]
changed = True
if not changed: break
return result
print(bubble_sort([4, 1, 3, 1]))[1, 1, 3, 4]
03 Under the hood
- 1
After each full pass the largest remaining value is at the pass’s final position. Later passes can stop before that sorted suffix.
- 2
The function copies its input, making its nonmutation contract clear. That copy uses additional linear space in this particular implementation.
- 3
Python’s sorted() creates a new sorted list and list.sort() mutates in place. Their stable ordering preserves the order of equal-key items, which is useful for predictable multi-field sorting.
04 Your turn, builder
Compare bubble_sort on an empty list, an already sorted list, and repeated values.
Reveal one possible solution +
def bubble_sort(values):
result = list(values)
for end in range(len(result) - 1, 0, -1):
for i in range(end):
if result[i] > result[i + 1]: result[i], result[i + 1] = result[i + 1], result[i]
return result
for values in [[], [1, 2], [2, 2, 1]]:
assert bubble_sort(values) == sorted(values)
print("Three sorting checks passed")05 Check your signal
What does a stable sort preserve?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.