Sorting Algorithms – Basics

Lesson 6 of 20

Watch 9 bubble to the end, the minimum snap into place and keys slide home — three O(n²) sorts, bar by bar.

The big picture

Meet the basics

Three classic sorts share one idea — grow a sorted region one element at a time — but they disagree wildly on how much work each step costs.

Bubble: neighbour swaps

Each pass walks the array swapping out-of-order neighbours; the biggest value bubbles to the end. [6, 2, 9, 4, 7] is done in 3 passes.

The early exit

A swapped flag lets bubble sort quit after a pass with zero swaps — already-sorted input finishes in one clean O(n) sweep.

Selection: fewest swaps

Hunt the minimum, swap it into place. At most n - 1 swaps ever — but always about n²/2 comparisons, good input or bad.

Insertion: shift and place

Take the next key and shift bigger values right to slot it in. Nearly-sorted data is nearly free: best case O(n).

All in-place, all O(n²)

All three sort inside the original array with O(1) extra memory, and all hit quadratic time on hostile input.