All algorithms
Sorting

Insertion Sort

Build the sorted part one card at a time — the way you sort a hand of cards.

TimeO(n²)SpaceO(1)CategorySorting

Insertion Sort keeps a sorted prefix at the front of the array. For each new element it walks backwards through that prefix, shifting larger values one slot to the right, until it finds the spot where the element belongs — then drops it in.

Unlike Bubble Sort it is genuinely useful in practice: on nearly-sorted data it runs in O(n) because the inner loop stops immediately, which is why real library sorts fall back to it for small or almost-ordered ranges.

Watching the shift is what makes it click — the value being inserted is held in `key` while the array physically opens a gap for it. AlgoLens shows that gap forming on every pass.

The code

insertion_sort.cpp
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> a = {5, 2, 9, 1, 7, 3};
    int n = a.size();

    for (int i = 1; i < n; i++) {
        int key = a[i];
        int j = i - 1;
        while (j >= 0 && a[j] > key) {
            a[j + 1] = a[j];
            j--;
        }
        a[j + 1] = key;
    }

    for (int x : a) cout << x << ' ';
    cout << '\n';
    return 0;
}
Open this in the visualizer

Now run your own Insertion Sort

AlgoLens traces your code — arrays, graphs, trees and recursion — from a real execution, so you see how it actually behaves, not a canned animation.

Paste your code

Keep going