Insertion Sort

A simple O(n²) sorting algorithm that is surprisingly fast on small or nearly sorted arrays.


Context

Insertion sort is rarely taught as a “good” algorithm, yet it appears in real systems.

Why:


Core idea

After each iteration, the sorted prefix grows by one.


Properties


Implementation

class InsertionSort {
    void sort(int[] array) {
        for (var i = 1; i < array.length; i++) {
            var value = array[i];
            var previousIndex = i - 1;
            
            while (previousIndex >= 0 && array[previousIndex] > value) {
                array[previousIndex + 1] = array[previousIndex];
                previousIndex--;
            }
            
            array[previousIndex + 1] = value;
        }
    }
}