Sorting Algorithms – Basics

Lesson 6 of 20

Watch the biggest bar bubble home, a key slide into a sorted hand, and every pass shrink the unsorted rest.

The big picture

Three ways to sort

Bubble, selection and insertion are the O(n²) trio — simple, in-place, and still the right tool for small or nearly-sorted data.

The O(n²) trio

All three use nested compare loops: roughly n²/2 comparisons for n items. Fine for 50 exam scores, painful for a million rows.

Bubble

Compare neighbours, swap when the left one is bigger. The largest value bubbles to the end each pass, and a swapped flag exits early once a pass changes nothing.

Selection

Scan the unsorted rest for the minimum, swap it to the front. Exactly n-1 swaps on every input — the fewest writes of the trio.

Insertion

Sorts like a hand of cards: lift the next key, shift bigger cards one slot right, drop the key into the gap. O(n) on nearly-sorted data.

Stability

Bubble and insertion keep equal keys in their original order; selection can reverse them. That matters when sorting by one column of many.

Still everywhere

std::sort hands tiny runs to insertion sort, and interviewers warm up with these three — master them before the O(n log n) big leagues.