M13 · Sorting

Bubble, Selection and Insertion Sort

Bubble, selection and insertion sort all cost Θ(n²) comparisons in the worst case, but they are not interchangeable. Selection sort does the fewest writes, insertion sort is fast on nearly sorted data and powers the small cases of real library sorts, and only bubble and insertion sort are stable. The lab on this page runs selection sort; bubble and insertion sort have their own visualizers.

~40 minBeginnerC# · Python · Java · C++
Curriculum: M13 Sorting · 5 of 5 lessons available

You will be able to

  • Trace bubble, selection and insertion sort by hand and state the invariant each outer loop maintains.
  • Give exact best- and worst-case comparison counts and the number of swaps or shifts for each.
  • Explain why selection sort is not stable and why bubble and insertion sort are.
  • Use the number of inversions to predict the work bubble and insertion sort do on nearly sorted input.
  • Say where insertion sort is still used inside the built-in sorts of C#, Python, Java and C++.

Helpful before this lesson

  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.
  • M05 Arrays — Contiguous storage, index arithmetic, and how a dynamic array grows while keeping append cheap.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Three ways to grow a sorted region

All three algorithms keep a sorted region and grow it by one element per pass. They differ in where the region lives and how the next element joins it.

Algorithm Sorted region One pass
Bubble sort the end of the array, final values walk left to right, swapping neighbours that are out of order; the largest remaining value "bubbles" to the end
Selection sort the front, final values scan the unsorted part for its minimum and swap it to the front of that part
Insertion sort the front, sorted among themselves but not final take the next element and shift larger ones right until its place opens

The lab above runs selection sort. Bubble sort and insertion sort have their own visualizers with the same controls and the same 3D array: bubble sort visualizer and insertion sort visualizer. Try the same input in all three.

Selection sort

For each position i from 0 to n − 2:

  1. Assume the minimum of items[i..] is at i (minIndex = i).
  2. Compare every later element with the current minimum; a strictly smaller one becomes the new minimum.
  3. Swap items[i] with items[minIndex] (skip it if they are the same slot).

Invariant: before pass i, slots 0..i−1 hold the i smallest values in sorted order, and they never move again. In the lab, final slots turn green from the left.

Selection sort does the same comparisons whatever the input: n − 1 in the first pass, n − 2 in the next, so always n(n − 1)/2. Even a sorted array costs 28 comparisons for eight elements (the Already sorted preset). In exchange it makes at most n − 1 swaps, fewer than either of the others in the worst case. That is its one real strength: when writing an element is far more expensive than comparing two, selection sort minimises writes.

Why selection sort is not stable

Run the Not stable preset: 5a 5b 1. The minimum, 1, is at index 2, so the first pass swaps it with index 0. That long-distance swap throws 5a past 5b:

5a 5b 1   →   1 5b 5a

Nothing later puts them back, because 5b is not strictly smaller than 5a. The swap is the problem, not the comparison: replacing it with "remove the minimum and shift everything between right by one" makes selection sort stable, at the price of O(n²) writes.

Bubble sort

Each pass compares neighbours items[i] and items[i + 1] from left to right and swaps them when the right one is strictly smaller. After pass k the k largest values are final at the end. The early exit is what makes bubble sort worth discussing: if a whole pass makes no swap, every neighbouring pair is in order, so the array is sorted and the algorithm stops. On sorted input that is one pass and n − 1 comparisons.

Bubble sort is stable because it only ever swaps neighbours, and only when they are strictly out of order: two equal values are never swapped, so they cannot pass each other.

Insertion sort

For each i from 1 to n − 1: lift key = items[i] out, then walk left from i − 1, shifting every element strictly greater than key one slot right. Drop key into the gap.

Invariant: before step i, slots 0..i−1 are sorted among themselves (they are the first i input values, rearranged). Unlike selection sort, they are not final: a later small key can still push them right.

Insertion sort is stable (equal elements stop the shifting, so the key lands after them), works in place, and is online: it can sort elements as they arrive, because each step only needs the elements seen so far.

Inversions: why nearly sorted input is cheap

An inversion is a pair of positions i < j with items[i] > items[j]. A sorted array has 0, a reversed one has n(n − 1)/2, and a random permutation has n(n − 1)/4 on average.

Swapping two neighbours that are out of order removes exactly one inversion. So:

  • bubble sort makes exactly one swap per inversion, and
  • insertion sort makes exactly one shift per inversion, with at most n − 1 extra comparisons.

If every element is at most k places from its final position, there are at most about n·k inversions, and insertion sort runs in O(n·k). This is why insertion sort is the algorithm of choice for "almost sorted" data and for small ranges.

Side by side

Bubble (early exit) Selection Insertion
Comparisons, best n − 1 (sorted) n(n − 1)/2 n − 1 (sorted)
Comparisons, worst n(n − 1)/2 n(n − 1)/2 n(n − 1)/2
Element moves 1 swap per inversion ≤ n − 1 swaps 1 shift per inversion + n − 1 placements
Stable yes no (swap version) yes
Adaptive (faster on nearly sorted) yes no yes
Extra space O(1) O(1) O(1)

All three are Θ(n²) in the worst case and on average. Insertion sort usually beats bubble sort in practice: a shift is one write where a swap is two (or three with a temporary), and insertion sort stops scanning as soon as the key's place is found.

Where these still run

You will rarely call a quadratic sort yourself, but the built-in sorts call insertion sort for you:

  • Python (list.sort, sorted): Timsort extends short natural runs to a minimum length (between 32 and 64) with binary insertion sort, then merges runs.
  • C# (Array.Sort, List<T>.Sort): an introspective sort that switches to insertion sort for small partitions.
  • C++ (std::sort in libstdc++ and libc++): introsort that finishes small ranges with insertion sort.
  • Java (Arrays.sort for primitives): a dual-pivot quicksort that uses insertion sort for very small ranges; the object sort (TimSort) uses binary insertion sort for short runs, like Python.

The exact thresholds are implementation details that change between versions. The pattern does not: divide-and-conquer sorts have a high constant per call, and below a few dozen elements insertion sort's tight loop over contiguous memory wins.

The teaching implementation

SelectionSort.Sort / selection_sort takes a comparison (or a key in Python). Because selection sort is unstable, its shared fixture records the exact order this implementation leaves equal keys in, for example 3a 1 3b 2 3c → 1 2 3b 3a 3c, and all four languages must reproduce it. Each is also compared with its built-in sort on 500 random inputs (keys only, since the order of equal keys may legitimately differ). Bubble sort and insertion sort are tested against the stable merge sort fixture; their listings are on their visualizer pages.

Common mistakes

  • Swapping on <= in bubble sort or shifting on >= in insertion sort: still sorted, no longer stable.
  • Forgetting the early exit in bubble sort, which turns its best case into n(n − 1)/2.
  • Updating minIndex with <= in selection sort: picks the last of equal minimums. Both versions are unstable, but they give different orders, so tests that pin down the exact output must agree on one.
  • Insertion sort writing the key on every shift instead of once at the end: correct, but twice the writes.

Worked practice

1. How many inversions does 3 1 2 have, and how many swaps will bubble sort make?

Answer

Two inversions: (3, 1) and (3, 2). Bubble sort makes exactly two swaps: 3 passes 1, then 3 passes 2.

2. You sort 1,000 records that were sorted yesterday and then had 5 records changed. Which elementary sort do you pick?

Answer

Insertion sort. Each changed record creates at most n inversions, so there are at most about 5,000, and insertion sort does roughly that many shifts plus n comparisons, far below the roughly 500,000 comparisons selection sort always makes.

3. Selection sort on 2a 2b 2c 1. What is the result?

Answer

1 2b 2c 2a. The first pass swaps 1 with 2a (index 0 ↔ 3). The remaining passes find 2b and then 2c already in place (only strictly smaller values replace the minimum), so no more swaps.

Summary

  • All three grow a sorted region one element per pass and cost Θ(n²) comparisons in the worst case.
  • Selection sort: always n(n − 1)/2 comparisons, at most n − 1 swaps, not stable.
  • Bubble and insertion sort: one swap or shift per inversion, stable, linear on sorted input.
  • Insertion sort is the small-range workhorse inside Python's, C#'s, Java's and C++'s library sorts.

Full implementation

Selection sort in four languages, each checked against one shared fixture that pins down the exact (unstable) order of equal keys, and 500 random inputs whose keys are compared with the language's built-in sort.

namespace Bekadan.Dsa.Examples.Sorting;
 
/// <summary>
/// Selection sort: in place, not stable. Always n(n - 1)/2 comparisons,
/// at most n - 1 swaps.
/// </summary>
public static class SelectionSort
{
    public static void Sort<T>(T[] items, Comparison<T> compare)
    {
        for (int i = 0; i < items.Length - 1; i++)
        {
            int minIndex = i; // smallest of items[i..] seen so far
            for (int j = i + 1; j < items.Length; j++)
            {
                if (compare(items[j], items[minIndex]) < 0) // strictly smaller: the first minimum wins ties
                {
                    minIndex = j;
                }
            }
            if (minIndex != i)
                (items[i], items[minIndex]) = (items[minIndex], items[i]); // can jump over equal items: not stable
        }
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Sorting/SelectionSort.cs

"""Selection sort: in place, not stable.
 
Always n(n - 1)/2 comparisons and at most n - 1 swaps.
"""
 
from collections.abc import Callable
from typing import Any
 
 
def _identity(item: Any) -> Any:
    return item
 
 
def selection_sort(items: list[Any], key: Callable[[Any], Any] = _identity) -> None:
    for i in range(len(items) - 1):
        min_index = i  # smallest of items[i:] seen so far
        for j in range(i + 1, len(items)):
            if key(items[j]) < key(items[min_index]):  # strictly smaller: the first minimum wins ties
                min_index = j
        if min_index != i:
            items[i], items[min_index] = items[min_index], items[i]  # can jump over equal items: not stable

Tested on CPython 3.14.0 · examples/python/dsa_examples/selection_sort.py

package dev.bekadan.dsa.sorting;
 
import java.util.Comparator;
 
/**
 * Selection sort: in place, not stable. Always n(n - 1)/2 comparisons,
 * at most n - 1 swaps.
 */
public final class SelectionSort {
    private SelectionSort() {
    }
 
    public static <T> void sort(T[] items, Comparator<? super T> comparator) {
        for (int i = 0; i < items.length - 1; i++) {
            int minIndex = i; // smallest of items[i..] seen so far
            for (int j = i + 1; j < items.length; j++) {
                if (comparator.compare(items[j], items[minIndex]) < 0) { // strictly smaller: the first minimum wins ties
                    minIndex = j;
                }
            }
            if (minIndex != i) { // can jump over equal items: not stable
                T tmp = items[i];
                items[i] = items[minIndex];
                items[minIndex] = tmp;
            }
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/sorting/SelectionSort.java

#pragma once
 
#include <cstddef>
#include <functional>
#include <span>
#include <utility>
 
namespace bekadan::dsa {
 
// Selection sort: in place, not stable. Always n(n - 1)/2 comparisons,
// at most n - 1 swaps.
 
template <typename T, typename Less = std::less<>>
void selection_sort(std::span<T> items, Less less = {}) {
    for (std::size_t i = 0; i + 1 < items.size(); ++i) {
        std::size_t min_index = i;  // smallest of items[i..] seen so far
        for (std::size_t j = i + 1; j < items.size(); ++j) {
            if (less(items[j], items[min_index])) {  // strictly smaller: the first minimum wins ties
                min_index = j;
            }
        }
        if (min_index != i)
            std::swap(items[i], items[min_index]);  // can jump over equal items: not stable
    }
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/selection_sort.hpp

References