Merge Sort
Split until single elements, then merge sorted halves back together — O(n log n), always.
Merge Sort is divide and conquer: split the array in half, sort each half recursively, then merge the two sorted halves by repeatedly taking the smaller front element. The recursion bottoms out at single elements, which are sorted by definition.
Its O(n log n) bound holds for every input — no worst case to worry about — and it is stable, so equal elements keep their original order. The price is O(n) extra space for the merge buffer.
The hard part to picture is the order of operations: the recursion goes all the way down the left side before any merging happens. AlgoLens shows the call tree next to the array, so you see exactly which range is being merged and when.
The code
#include <bits/stdc++.h>
using namespace std;
vector<int> a = {5, 2, 9, 1, 7, 3};
void merge_(int lo, int mid, int hi) {
vector<int> tmp;
int i = lo, j = mid + 1;
while (i <= mid && j <= hi) {
if (a[i] <= a[j]) tmp.push_back(a[i++]);
else tmp.push_back(a[j++]);
}
while (i <= mid) tmp.push_back(a[i++]);
while (j <= hi) tmp.push_back(a[j++]);
for (int k = 0; k < (int)tmp.size(); k++) a[lo + k] = tmp[k];
}
void mergeSort(int lo, int hi) {
if (lo >= hi) return;
int mid = (lo + hi) / 2;
mergeSort(lo, mid);
mergeSort(mid + 1, hi);
merge_(lo, mid, hi);
}
int main() {
mergeSort(0, a.size() - 1);
for (int x : a) cout << x << ' ';
cout << '\n';
return 0;
}
Now run your own Merge 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.
Insertion Sort
Build the sorted part one card at a time — the way you sort a hand of cards.
Selection Sort
Find the smallest remaining value each pass and swap it into place.
Quick Sort
Partition around a pivot, then recurse — the fastest sort in practice.