Menu
Coddy logo textTech

Merge Sort

Last updated

Merge sort is a divide-and-conquer algorithm. It recursively splits the array in half until each piece has a single element (which is trivially sorted), then merges the pieces back together in order. The merge step walks two sorted subarrays with two pointers, always copying the smaller front element next. Press play above to watch the array get rebuilt merge by merge.

Because it always splits in half, merge sort runs in O(n log n) time in every case - its worst case is as good as its best. The trade-off is O(n) extra space for the temporary merge buffer.

Time & space complexity

CaseComplexityNotes
Best caseO(n log n)Always halves the input
Average caseO(n log n)Random order
Worst caseO(n log n)Guaranteed - no bad inputs
SpaceO(n)Temporary buffer for merging
StableYesTies resolved left-first during merge

Step by step

StepWhat happens
1If the range has 0 or 1 elements, it is already sorted.
2Split the range into two halves.
3Recursively merge-sort the left half.
4Recursively merge-sort the right half.
5Merge the two sorted halves with two pointers.

Worked example

Sorting [5, 2, 4, 1]:

PassArrayAction
Split[5, 2] | [4, 1]Divide the array into two halves
Split[5] [2] | [4] [1]Divide again until each piece is a single element
Merge[2, 5] | [1, 4]Merge [5],[2] into [2, 5] and [4],[1] into [1, 4]
Merge[1, 2, 4, 5]Merge [2, 5] and [1, 4]: pick 1, then 2, then 4, then 5
Done[1, 2, 4, 5]Array is fully sorted

When to use merge sort

Use it whenAvoid it when
You need a guaranteed O(n log n) worst caseMemory is tight and O(n) extra space is unacceptable
Stability matters (equal keys keep their order)You are sorting small arrays where insertion sort is faster
You are sorting a linked listIn-place sorting is a hard requirement
Data is too large for RAM (external sorting)Cache locality dominates and quicksort's in-place passes win

Merge Sort code

A clean, runnable Merge Sort implementation in Python, JavaScript, Java, C++, C. Pick a language, copy the code, or open it pre-loaded in the Coddy Playground.

Merge Sort code in Python

Python
1def merge_sort(a):2    if len(a) <= 1:3        return a4    mid = len(a) // 25    left = merge_sort(a[:mid])6    right = merge_sort(a[mid:])7    return merge(left, right)8
9
10def merge(left, right):11    out = []12    i = j = 013    while i < len(left) and j < len(right):14        if left[i] <= right[j]:15            out.append(left[i])16            i += 117        else:18            out.append(right[j])19            j += 120    out.extend(left[i:])21    out.extend(right[j:])22    return out23
24
25nums = [38, 27, 43, 3, 9, 82, 10]26print("Before:", nums)27print("After: ", merge_sort(nums))
Run this code in the Python Playground

Merge Sort FAQ

What is the time complexity of merge sort?
Merge sort is O(n log n) in the best, average, and worst cases, because it always divides the array in half. It uses O(n) extra space for the merge buffer.
Is merge sort stable?
Yes, when the merge step resolves ties by taking from the left half first. This keeps equal elements in their original relative order, which is why merge sort is a common choice for stable sorting.
Why use merge sort over quicksort?
Merge sort guarantees O(n log n) even on adversarial inputs and is stable, whereas quicksort can degrade to O(n²). Merge sort is also preferred for linked lists and external sorting. The downside is its O(n) extra memory.
What is the difference between merge sort and quicksort?
Both are divide-and-conquer sorts, but quicksort partitions around a pivot and sorts in place with O(log n) stack space, while merge sort splits blindly in half and merges using an O(n) buffer. Quicksort is usually faster in practice due to cache locality, but merge sort has a guaranteed O(n log n) worst case and is stable.
When should I use merge sort in practice?
Reach for merge sort when you need a stable sort with a guaranteed O(n log n) bound, when sorting linked lists (where it needs no random access), or when doing external sorting of data too large to fit in memory. Avoid it when memory is scarce, since it needs O(n) extra space.
Does merge sort sort in place?
No. Standard merge sort allocates an O(n) temporary buffer to merge the two halves, so it is not in-place. In-place merge variants exist but are complex and either slower or lose stability, so the buffer-based version is the common choice.
Coddy programming languages illustration

Master algorithms with Coddy

GET STARTED