64
34
25
12
22
11
90
0
1
2
3
4
5
6
Starting Merge Sort. Recursively dividing the array into halves.
Presets:
Size:
Timeline Progress:
0%Step 1 / 41
Comparisons
0
Swaps / Actions
0
Speed:
Shortcuts: Space Play • ←/→ Step • R Reset • M Sound • Z Focus
Implementation Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function mergeSort(arr: number[]): number[] {
if (arr.length <= 1) return arr;
const mid = Math.floor(arr.length / 2);
const left = mergeSort(arr.slice(0, mid));
const right = mergeSort(arr.slice(mid));
return merge(left, right);
}
function merge(left: number[], right: number[]): number[] {
const result: number[] = [];
let i = 0, j = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
result.push(left[i++]);
} else {
result.push(right[j++]);
}
}
return result.concat(left.slice(i)).concat(right.slice(j));
}Complexity Analysis
Best Case
O(n log n)
Average Case
O(n log n)
Worst Case
O(n log n)
Space
O(n)
Color Legend
Unsorted
Comparing
Swapping
Sorted
Merge Sort is a classic divide-and-conquer algorithm. It recursively divides the array into two halves until each sub-array has one element (which is trivially sorted), then merges those sorted halves back together. It guarantees O(n log n) time in all cases and is stable, making it ideal for sorting linked lists and external sorting scenarios.