Even sorted input crosses log n levels with n merge work per level, Ξ(n log n).
Sorting algorithms Β· 2/7
Merge sort
Divides the array, sorts both halves and merges them linearly.
How it works
Recursion splits down to singletons. Merge repeatedly copies the smaller front item from two sorted halves.
Step-by-step visualization
The bar view shows comparisons and copies; the parallel tree follows the array splits and the subsequent merges.
Use 2 to 16 values. This visualizer accepts values from 0 to 999.
- Comparisons
- 0
- Writes
- 0
- Swaps
- 0
- Pass / level
- 0
Pseudocode linked to the visualization
Merge sort
mergeSort(A, left, right)if left β₯ right: returnmid β β(left + right) / 2βmergeSort(A, left, mid)mergeSort(A, mid + 1, right)merge(A, left, mid, right)
Merge
merge(A, left, mid, right)L β A[left β¦ mid]R β A[mid + 1 β¦ right]i β 0; j β 0; B β empty arraywhile i < length(L) and j < length(R)if L[i] β€ R[j]append L[i] to B; i β i + 1elseappend R[j] to B; j β j + 1append the remaining elements of L or R to Bfor k β 0 to length(B) β 1A[left + k] β B[k]
The highlighted line corresponds to the operation described by the visualizer. Index-management details are intentionally simplified.
Complexity analysis
T(n)=2T(n/2)+Ξ(n)=Ξ(n log n), independent of input order.
The same log n levels give a Ξ(n log n) guarantee.
Array merge sort uses a Ξ(n) buffer and Ξ(log n) stack. Taking left on ties preserves stability.
Properties at a glance
Stability concerns the relative order of elements with equal keys.
This classification refers to the version shown on this page.
When to use it and what to avoid
A good choice whenβ¦
Strong when stability and a guarantee matter, and for linked lists or external sorting.
Common mistake
Taking from the right half on equal keys breaks stability.