Swap your way to understanding.
Trace a simple quadratic algorithm and understand why built-ins are the practical default.
01 Model 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.
After a pass, its final position contains the largest remaining value.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
REPEAT a pass over the unsorted prefix
compare each adjacent pair
swap if reversed
stop early if no pair changedStart with the original values. Predict the next comparison.
Change the experiment +
03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
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]
- 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 Count the cost
O(n²) worst case; O(n) best case with early exit
O(n) for the copied result
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
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")06 Check your reasoning
What does a stable sort preserve?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.