Insertion Sort
Build the sorted part one card at a time — the way you sort a hand of cards.
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
#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;
}
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 codeKeep going
Bubble Sort
The simplest sort — watch the largest value bubble to the end each pass.
Selection Sort
Find the smallest remaining value each pass and swap it into place.
Merge Sort
Split until single elements, then merge sorted halves back together — O(n log n), always.
Quick Sort
Partition around a pivot, then recurse — the fastest sort in practice.