Bubble sort — O(n²), teaching-only
referencebeginnerBubble sort repeatedly walks the array, swapping any adjacent out-of-order pair — each full pass "bubbles" the largest remaining unsorted value to its correct position at the end.
What we're doing: Sort a list by repeatedly bubbling the largest remaining value to the end, stopping early once a full pass makes no swaps.
- 6
- The inner loop shrinks by one each pass — the last i elements are already in their final position and never need rechecking.
- 9
- A pass with no swaps means the array is already sorted — stopping early is what keeps the best case O(n) instead of always O(n²).
[1, 2, 3, 4, 5, 6]Why this works: Each pass moves the largest unsorted value one step closer to its final spot at the end — after enough passes, every value has bubbled to its correct position.
Remember: Bubble sort is O(n²) and exists to teach the idea of repeated adjacent swaps — insertion sort covers the same practical niche with less real work.