Sorting · O(n²) worst, O(n) sorted
Insertion sort
Lift a key, shift larger elements right, drop it into the gap; stable.
The full explanation, derivation and practice are in the lesson Bubble, selection and insertion sort.
Implementation
The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.
namespace Bekadan.Dsa.Examples.Sorting;
/// <summary>
/// Bubble sort (with the early exit) and insertion sort. Both are stable and in
/// place: Θ(n²) comparisons in the worst case, Θ(n) on already sorted input.
/// </summary>
public static class ElementarySorts
{
public static void BubbleSort<T>(T[] items, Comparison<T> compare)
{
for (int end = items.Length - 1; end > 0; end--)
{
bool swapped = false;
for (int i = 0; i < end; i++)
{
if (compare(items[i + 1], items[i]) < 0) // strictly smaller: equal items never swap (stable)
{
(items[i], items[i + 1]) = (items[i + 1], items[i]);
swapped = true;
}
}
if (!swapped)
break; // no swap in a whole pass: already sorted
}
}
public static void InsertionSort<T>(T[] items, Comparison<T> compare)
{
for (int i = 1; i < items.Length; i++)
{
T key = items[i];
int j = i - 1;
while (j >= 0 && compare(items[j], key) > 0) // strictly greater: equal items stay in order (stable)
{
items[j + 1] = items[j];
j--;
}
items[j + 1] = key;
}
}
}
Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Sorting/ElementarySorts.cs
"""Bubble sort (with the early exit) and insertion sort.
Both are stable and in place: Θ(n²) comparisons in the worst case, Θ(n) on
already sorted input.
"""
from collections.abc import Callable
from typing import Any
def _identity(item: Any) -> Any:
return item
def bubble_sort(items: list[Any], key: Callable[[Any], Any] = _identity) -> None:
for end in range(len(items) - 1, 0, -1):
swapped = False
for i in range(end):
if key(items[i + 1]) < key(items[i]): # strictly smaller: equal items never swap (stable)
items[i], items[i + 1] = items[i + 1], items[i]
swapped = True
if not swapped:
break # no swap in a whole pass: already sorted
def insertion_sort(items: list[Any], key: Callable[[Any], Any] = _identity) -> None:
for i in range(1, len(items)):
current = items[i]
j = i - 1
while j >= 0 and key(items[j]) > key(current): # strictly greater: equal items stay in order (stable)
items[j + 1] = items[j]
j -= 1
items[j + 1] = current
Tested on CPython 3.14.0 · examples/python/dsa_examples/elementary_sorts.py
package dev.bekadan.dsa.sorting;
import java.util.Comparator;
/**
* Bubble sort (with the early exit) and insertion sort. Both are stable and in
* place: Θ(n²) comparisons in the worst case, Θ(n) on already sorted input.
*/
public final class ElementarySorts {
private ElementarySorts() {
}
public static <T> void bubbleSort(T[] items, Comparator<? super T> comparator) {
for (int end = items.length - 1; end > 0; end--) {
boolean swapped = false;
for (int i = 0; i < end; i++) {
if (comparator.compare(items[i + 1], items[i]) < 0) { // strictly smaller: equal items never swap (stable)
T tmp = items[i];
items[i] = items[i + 1];
items[i + 1] = tmp;
swapped = true;
}
}
if (!swapped) {
break; // no swap in a whole pass: already sorted
}
}
}
public static <T> void insertionSort(T[] items, Comparator<? super T> comparator) {
for (int i = 1; i < items.length; i++) {
T key = items[i];
int j = i - 1;
while (j >= 0 && comparator.compare(items[j], key) > 0) { // strictly greater: equal items stay in order
items[j + 1] = items[j];
j--;
}
items[j + 1] = key;
}
}
}
Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/sorting/ElementarySorts.java
#pragma once
#include <cstddef>
#include <functional>
#include <span>
#include <utility>
namespace bekadan::dsa {
// Bubble sort (with the early exit) and insertion sort. Both are stable and in
// place: Θ(n²) comparisons in the worst case, Θ(n) on already sorted input.
template <typename T, typename Less = std::less<>>
void bubble_sort(std::span<T> items, Less less = {}) {
for (std::size_t end = items.size(); end > 1; --end) {
bool swapped = false;
for (std::size_t i = 0; i + 1 < end; ++i) {
if (less(items[i + 1], items[i])) { // strictly smaller: equal items never swap (stable)
std::swap(items[i], items[i + 1]);
swapped = true;
}
}
if (!swapped)
break; // no swap in a whole pass: already sorted
}
}
template <typename T, typename Less = std::less<>>
void insertion_sort(std::span<T> items, Less less = {}) {
for (std::size_t i = 1; i < items.size(); ++i) {
T key = std::move(items[i]);
std::size_t j = i; // the gap is at j; compare with items[j - 1]
while (j > 0 && less(key, items[j - 1])) { // strictly greater on the left: equal items stay in order
items[j] = std::move(items[j - 1]);
--j;
}
items[j] = std::move(key);
}
}
} // namespace bekadan::dsa
Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/elementary_sorts.hpp