Algorithms · Visualized
Merge Sort
Sorting Algorithms
Seventeen sorting algorithms on the same shuffled data — watch comparisons, swaps, pivots and heaps rearrange bars step by step.
Merge Sort is a divide-and-conquer algorithm. Time: O(n log n) average, O(n log n) worst; space: O(n) — needs extra arrays for merging.
Big-O: Best O(n log n) comparison sorts; counting/radix/bucket reach O(n + k) on small integer keys.
Merge Sort
SortingMerge Sort is a divide-and-conquer algorithm. It repeatedly splits the array in half until each piece has just one element (which is trivially sorted), then merges those pieces back together in sorted order, two at a time.
How Merge Sort Works
- If the array has 1 or 0 elements, it's already sorted — this is the base case.
- Otherwise, split the array into two halves.
- Recursively sort the left half.
- Recursively sort the right half.
- Merge the two sorted halves into one sorted array by repeatedly picking the smaller of the two front elements.
Merge Sort Worked Example
Input: [38, 27, 43, 3, 9, 82, 10]
Split into [38,27,43,3] and [9,82,10]. Keep splitting down to single elements. Merge [38]&[27]→[27,38]; [43]&[3]→[3,43]; merge those→[3,27,38,43]. Merge [9]&[82]→[9,82]; merge with [10]→[9,10,82]. Finally merge [3,27,38,43] and [9,10,82] by comparing fronts → [3,9,10,27,38,43,82].
def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left, right = merge_sort(a[:mid]), merge_sort(a[mid:])
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
out.append(left[i]); i += 1
else:
out.append(right[j]); j += 1
return out + left[i:] + right[j:]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Merge Sort Time & Space Complexity
When to Use Merge Sort
- Sorting linked lists efficiently (no random access needed).
- External sorting, when data is too big to fit in memory (sort chunks, merge from disk).
- Anywhere a stable sort with guaranteed O(n log n) worst case is required.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.