V

Algorithm Visualizer

ZHEN
Share on WeiboShare on XGitHub repositoryAuthor website
Learning ToolsAlgorithm Complexity ReferenceAlgorithm Learning Paths
Data StructuresArrayLinked ListStackQueue and DequeBinary Search TreeBinary HeapHash TableGraphTrieDisjoint Set UnionLRU CacheSkip ListSegment TreeB+ TreeBloom FilterFenwick Tree
SortingBubble SortCocktail Shaker SortBitonic SortSelection SortInsertion SortBinary Insertion SortShell SortMerge SortTop-Down Merge SortQuick SortThree-Way Quick SortDual-Pivot Quick SortHeap SortCounting SortRadix SortBucket Sort
Graph AlgorithmsDijkstra's Shortest PathKruskal's Minimum Spanning TreePrim's Minimum Spanning TreeBellman-Ford Shortest PathsTopological SortFloyd-WarshallStrongly Connected Components2-SATMaximum FlowBipartite MatchingLowest Common AncestorEulerian Path
Dynamic ProgrammingEdit Distance0/1 KnapsackUnbounded KnapsackLongest Common SubsequenceLongest Increasing SubsequenceCoin ChangeStone MergingTraveling Salesperson DPTree Dynamic ProgrammingDigit DPRerooting DP
Backtracking and SearchN-QueensSubsetsPermutationsCombination SumMaze Solving with DFSNumber of IslandsWord SearchSudoku SolverA* Search
StringsKMP String MatchingRabin-Karp String MatchingBoyer-Moore String MatchingManacher's Longest Palindromic SubstringSuffix ArrayLCP ArrayAho-Corasick AutomatonZ Function
Math and Number TheorySieve of EratosthenesLinear SieveEuclidean AlgorithmBinary ExponentiationExtended Euclidean AlgorithmChinese Remainder TheoremEuler's Totient FunctionMiller-Rabin Primality TestFast Fourier TransformPollard's Rho Factorization
Computational GeometryConvex HullRotating CalipersClosest Pair of PointsLine Segment IntersectionBentley-Ottmann Sweep Line
SearchingBinary SearchLower and Upper BoundSearch in a Rotated Sorted ArrayBinary Search on the AnswerTernary Search

Merge Sort

Stable bottom-up sorting through ordered runs and an auxiliary array

Merge small sorted runs into larger ones

A one-element run is already sorted. Bottom-up Merge Sort first combines neighboring runs of width 1, then width 2, width 4, and so on. Each merge repeatedly takes the smaller front value from two sorted ranges.

Follow the main and auxiliary tracks

Red and blue pointers mark the front of the left and right runs. The lower track is the temporary array: values enter it in sorted order, then the completed range is copied back to the main array. Stable element IDs make that write-back visible without changing the algorithm's meaning.

7
6
5
10
9
8
4
3
2
1

Set run width to 1; merge adjacent sorted runs of this size.

1function mergeSort(a: number[]): number[] {
2 const n = a.length;
3 const temp = new Array(n);
4 for (let width = 1; width < n; width *= 2) {
5 for (let lo = 0; lo < n; lo += 2 * width) {
6 const mid = Math.min(lo + width, n);
7 const hi = Math.min(lo + 2 * width, n);
8 let i = lo, j = mid, k = lo;
9 while (i < mid && j < hi) {
10 if (a[i] <= a[j]) {
11 temp[k++] = a[i++];
12 } else {
13 temp[k++] = a[j++];
14 }
15 }
16 while (i < mid) temp[k++] = a[i++];
17 while (j < hi) temp[k++] = a[j++];
18 for (let t = lo; t < hi; t++) a[t] = temp[t];
19 }
20 }
21 return a;
22}
n10
width1
lo-
mid-
hi-
i-
j-
k-
a[i]-
a[j]-
writeCount0
1 / 78

Predictable performance

Every level processes all n values, and there are log n run widths, so time is O(n log n) in the best, average, and worst cases. This array version uses O(n) auxiliary space and remains stable by taking the left value first on a tie.

Merge invariant: before writing position k, the filled temporary prefix is sorted and contains exactly the smallest values consumed from both runs.

Compare the auxiliary-array tradeoff with in-place Heap Sort.