Sorting Algorithms – Basics

Lesson 6 of 20

Bars bubble, select and insert their way into order — every compare and swap of the three basic sorts, live on screen.

The big picture

Three first sorts

Bubble, selection and insertion are the O(n²) classics — simple enough to trace on paper and honest enough to show what sorting really costs.

Bubble

Compare neighbours, swap if out of order. Each pass locks the biggest remaining value into place at the end.

Selection

Scan for the smallest value, swap it to the front. Always exactly n − 1 swaps, no matter the input.

Insertion

Grow a sorted zone on the left, shift each new value into its slot. Nearly-sorted input makes it fly.

Best vs worst

Insertion on sorted input: zero shifts, O(n). All three on a reversed list: O(n²) — n(n−1)/2 comparisons.

The exit flag

A bubble pass with zero swaps proves the list is sorted — the early-exit trick turns 5 passes into 4.