AlgoLab
AlgorithmsCompare
AlgoLab
AlgorithmsCompareGitHub

© 2026 AlgoLab. Open source.

AlgorithmsSortingInsertion Sort
Sortingbeginnercomparisonstablein-placeadaptiveonline

Insertion Sort

Insertion Sort works like sorting a hand of playing cards. It iterates through the array, and for each element it shifts larger elements one position right to make room, then inserts the current element. It is efficient for small arrays and nearly-sorted data, and is the basis of Tim Sort.

Complexity

Best
O(n)
Average
O(n²)
Worst
O(n²)
Space
O(1)
Stable
Yes
In-Place
Yes

Visualizer

Implementation

void insertionSort(vector<int>& arr) {
    int n = arr.size();
    for (int i = 1; i < n; i++) {
        int key = arr[i], j = i - 1;
        while (j >= 0 && arr[j] > key) {
            arr[j+1] = arr[j];
            j--;
        }
        arr[j+1] = key;
    }
}

How It Works

1.How It Works

Insertion Sort maintains a sorted prefix. For each new element it scans backward through the sorted prefix, shifting elements right until the correct insertion point is found.

2.Online Algorithm

Insertion Sort is online: it can sort a list as it receives elements one by one without needing the full input upfront. This makes it ideal for streaming data scenarios.

3.Performance on Nearly-Sorted Data

When the array is nearly sorted, each element requires very few shifts. Best case is O(n) when the input is already sorted — only one comparison per element.

4.Use in Practice

Insertion Sort is used for small subarrays (typically n < 16) in hybrid algorithms like Tim Sort and Intro Sort, where its low overhead beats the O(n log n) algorithms due to smaller constant factors.

Related Algorithms

ArrowUpDownBubble SortArrowUpDownShell SortArrowUpDownTim Sort

Test Your Knowledge

1.

Insertion Sort is most efficient when:

2.

What is the worst-case time complexity of Insertion Sort?

3.

Which real-world use case favors Insertion Sort?

0/3 answered
Back to all algorithms