Foundation · Module 4 · Lesson 1
Bubble Sort
Adjacent swaps and a growing sorted suffix.
Lesson 19 of 123
1d streakInteractive Visualization
Trace the algorithm state by state
Change the inputs, run an operation, and connect each visible state change to the explanation below.
Step-through visualizer
Bubble Sort
Follow the state transition, then use the controls to test your prediction.
Theory lesson · Step-by-step
Understand Bubble Sort
Adjacent swaps and a growing sorted suffix.
Worked approach
Trace the reasoning step by step
- 1Identify the sorted region maintained by Bubble Sort.
- 2Choose or compare the next candidate according to the algorithm.
- 3Move values while preserving multiplicity and ordering requirements.
- 4Grow the sorted region and prove that at least one value becomes final.
- 5Check duplicates, stable-order requirements, sorted input, and reverse input.
Concrete example
Sort [5, 1, 4, 2] with adjacent swaps.
- 1Pass 1 moves 5 right → [1,4,2,5].
- 2Pass 2 → [1,2,4,5].
- 3No-swap pass stops early.
Each pass finalizes a sorted suffix.
What must remain true (Loop Invariant)
After each stage of Bubble Sort, the declared sorted region is final and the remaining values still contain every unplaced element.
Reference pseudocode
Verify your trace
- • Write the state after every step.
- • Confirm the invariant still holds.
- • Count visited states to derive complexity.
- • Repeat with an edge-case input.
Cost Model
Complexity & Trade-offs
When to use it
- Creating order before searching, grouping, deduplicating, or scanning.
- Selecting records using stability, memory, and input-shape constraints.
- Turning pairwise decisions into monotonic scans.
Common mistakes
- Comparing time alone while ignoring stability and auxiliary memory.
- Breaking duplicate order when stability is required.
- Quoting average performance without worst-case behavior.
Practice prompts
- Reproduce the worked Bubble Sort example without looking at the trace.
- Change one input condition and explain whether the Bubble Sort invariant still holds.
- Implement the approach, derive its cost, and compare it with a straightforward baseline.
Mastery check