Simple Sorts

Quadratic-time comparison sorts that are easy to reason about: bubble, insertion, selection and Shell sort.

Simple sorts are the quadratic comparison sorts: easy to write, easy to prove correct, and genuinely useful for small or nearly-sorted inputs. Production sorting routines such as Timsort and introsort still fall back to insertion sort for short runs, so understanding these algorithms is practical, not only historical.

Bubble Sort

Bubble sort repeatedly steps through the list, swapping adjacent out-of-order pairs until a pass makes no swaps. It is the canonical "first sort you learn&

Insertion Sort

Insertion sort builds a sorted prefix one element at a time, shifting each new element back to its correct position. It is fast on small or nearly-sorted…

Selection Sort

Selection sort repeatedly finds the minimum of the unsorted suffix and swaps it into place. It is O(n²) on every input — never adaptive — but it makes the…

Shell Sort

Shell sort generalizes insertion sort by sorting elements that are positions apart, then shrinking the gap until it reaches 1. By the time gap = 1, the array…

1. How they relate

One Pass of Each Simple Sort on [5, 2, 4, 1] Bubble swap adjacent pairs [2, 4, 1, 5] largest bubbles to end Selection swap min into slot 0 [1, 2, 4, 5] one swap per pass Insertion insert a[1] into prefix [2, 5, 4, 1] prefix grows by one

All four algorithms grow a sorted region one element at a time; they differ in how they choose the next element and how much data they move. Bubble sort swaps adjacent out-of-order pairs, so the largest remaining value drifts to the end each pass. Selection sort scans for the minimum and performs a single swap per pass. Insertion sort takes the next unsorted element and shifts it left into the sorted prefix. Shell sort runs insertion sort over elements that are a gap apart, shrinking the gap until it reaches one, which moves far-away elements quickly and beats the plain quadratic sorts in practice.

2. Comparison

AlgorithmBestAverageWorstSpaceStableAdaptive
Bubble SortO(n)O(n²)O(n²)O(1)YesYes (early exit)
Insertion SortO(n)O(n²)O(n²)O(1)YesYes
Selection SortO(n²)O(n²)O(n²)O(1)NoNo
Shell SortO(n log n)gap-sequence dependentO(n²) for Shell's gapsO(1)NoPartly

3. When to use which

For general-purpose sorting of large inputs use the language's built-in sort, which is an O(n log n) hybrid. The Mergesort and Timsort pages explain how those hybrids use insertion sort internally.