Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ The sorting workshop
EXPERIMENT 19 / 66

Swap your way to understanding.

Trace a simple quadratic algorithm and understand why built-ins are the practical default.

BY NAVAN SAMI◷ 8 MIN READCOREALGORITHM

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.

THE THING THAT MUST STAY TRUE

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.

the_strategy.txt
REPEAT a pass over the unsorted prefix
  compare each adjacent pair
  swap if reversed
  stop early if no pair changed
ALGORITHM STUDIOLIVE IN YOUR BROWSER
38
0
12
1
57
2
24
3
8
4
46
5
31
6
COMPARISONS 0ARRAY WRITES 0STEP 1/38

Start with the original values. Predict the next comparison.

Change the experiment +
Current operation Ordered / visitedPredict. Step. Explain.

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

sorting_basics.py
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]))
↳ EXPECTED OUTPUT
[1, 1, 3, 4]
  1. 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. 2

    The function copies its input, making its nonmutation contract clear. That copy uses additional linear space in this particular implementation.

  3. 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

TIME

O(n²) worst case; O(n) best case with early exit

SPACE

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

A SMALL MISSION

Compare bubble_sort on an empty list, an already sorted list, and repeated values.

Reveal one possible solution +
one_possible_solution.py
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

QUICK SIGNAL CHECK

What does a stable sort preserve?

ANOTHER PATTERN IN YOUR TOOLKIT.

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.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.