Merge sort
Split the array in half, sort each half, merge the two sorted halves.
Syllabus says: “Merge Sort”
On this page · 17 sections
SPLIT in half until single elements, then MERGE sorted halves. T(n) = 2T(n/2) + n = O(n log n) — always.
Two friends each sort half of the answer sheets, then merge their piles by repeatedly taking the smaller top sheet.
Merge sort divides the array into two halves, recursively sorts each half and merges the two sorted halves into one sorted array.
Learning objectives
- Draw the split tree and the merge sequence.
- Write the merge procedure.
- Solve T(n) = 2T(n/2) + n to get O(n log n).
Prerequisites
Recursion; merging two sorted lists.
Definition
Merge sort recursively sorts a[lo..mid] and a[mid+1..hi] (mid = ⌊(lo+hi)/2⌋) and then merges the two sorted halves using a temporary array.
How merging works
Copy the halves to L and R. Repeatedly compare the front elements of L and R and move the smaller one into a. When one list runs out, copy the rest of the other. Taking from L on ties keeps the sort stable.
Where it is used
External sorting of files too large for memory, sorting linked lists, and as the basis of the stable sorts in many standard libraries (e.g. TimSort in Python and Java).
Worked example
| Input | 38 27 43 3 9 82 10 |
|---|---|
| After merge 1: a[0..1] | 27 38 43 3 9 82 10 |
| After merge 2: a[2..3] | 27 38 3 43 9 82 10 |
| After merge 3: a[0..3] | 3 27 38 43 9 82 10 |
| After merge 4: a[4..5] | 3 27 38 43 9 82 10 |
| After merge 5: a[4..6] | 3 27 38 43 9 10 82 |
| After merge 6: a[0..6] | 3 9 10 27 38 43 82 |
Totals: comparisons = 14, writes = 20, merges = 6
Now watch it run
Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶. Keys: Space play/pause, ← → step.
Algorithm
- Step 1:Start.
- Step 2:Read the number of elements n and the n elements into the array A.
- Step 3:Call MergeSort(A, 0, n-1).
- Step 4:MergeSort(A, low, high): if low < high, go to Step 5; otherwise return.
- Step 5:Set mid = (low + high) / 2.
- Step 6:Call MergeSort(A, low, mid).
- Step 7:Call MergeSort(A, mid+1, high).
- Step 8:Call Merge(A, low, mid, high).
- Step 9:When the call in Step 3 is finished, display the sorted array A.
- Step 10:Stop.
- Step 1:Start.
- Step 2:Set i = low, j = mid + 1 and k = low.
- Step 3:Repeat Steps 4 and 5 while i <= mid and j <= high.
- Step 4:If A[i] <= A[j], copy A[i] to temp[k] and increment i; otherwise copy A[j] to temp[k] and increment j.
- Step 5:Increment k.
- Step 6:Copy the elements that are left:
- While i <= mid, copy A[i] to temp[k] and increment i and k (rest of the first half).
- While j <= high, copy A[j] to temp[k] and increment j and k (rest of the second half).
- Step 7:For i = low to high, copy temp[i] back to A[i].
- Step 8:Stop.
Pseudocode used by the animated lab · the lines highlighted in the visualizer
- 1MergeSort(a, lo, hi)
- 2if lo ≥ hi: return
- 3mid ← ⌊(lo + hi)/2⌋; MergeSort(lo, mid); MergeSort(mid+1, hi)
- 4Merge(a, lo, mid, hi): L ← a[lo..mid]; R ← a[mid+1..hi]
- 5while both non-empty: a[k++] ← smaller of L[i], R[j] (L on ties)
- 6copy whatever remains of L or R
- 7end
C implementation
merge_sort.ctested ✓ 228/228 cases/* Merge Sort — KTU PCCST303, Module 4 (lab-record style) */
#include <stdio.h>
void merge(int a[], int low, int mid, int high)
{
int temp[100], i, j, k;
i = low;
j = mid + 1;
k = low;
while (i <= mid && j <= high) { /* copy the smaller element */
if (a[i] <= a[j]) {
temp[k] = a[i];
i++;
}
else {
temp[k] = a[j];
j++;
}
k++;
}
while (i <= mid) { /* rest of the first half */
temp[k] = a[i];
i++;
k++;
}
while (j <= high) { /* rest of the second half */
temp[k] = a[j];
j++;
k++;
}
for (i = low; i <= high; i++) /* copy temp back to a */
a[i] = temp[i];
}
void mergeSort(int a[], int low, int high)
{
int mid;
if (low < high) {
mid = (low + high) / 2;
mergeSort(a, low, mid);
mergeSort(a, mid + 1, high);
merge(a, low, mid, high);
}
}
int main()
{
int a[100], n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter array elements:\n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
mergeSort(a, 0, n - 1);
printf("Sorted array: ");
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
Sample input / output · KTU PYQ input · real run, compiled with gcc
Enter number of elements: 8 Enter array elements: 45 33 56 22 76 78 40 30 Sorted array: 22 30 33 40 45 56 76 78
Bold = what you type. Everything else is printed by the program.
Complexity
T(n) = 2T(n/2) + cn ⇒ T(n) = O(n log n)
There are about log₂ n levels of splitting, and each level does O(n) work merging. This is the same in the best, average and worst case. Extra space is O(n) for the temporary arrays.
Advantages and disadvantages
| Advantages | Disadvantages |
|---|---|
| Guaranteed O(n log n) | Needs O(n) extra memory |
| Stable; works well on linked lists | Slower than quick sort on arrays in practice |
Common mistakes
- Splitting unevenly and then forgetting which half gets the extra element — state mid = ⌊(lo+hi)/2⌋.
- Forgetting to copy the leftover elements after the main merge loop.
- Saying merge sort is in-place.
Asked in KTU exams (1)
Quick check — can you get them all?
Practice
Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.
Exam-ready summary
- Divide (split at mid), conquer (sort halves), combine (merge).
- O(n log n) all cases; O(n) extra space; stable.
References
- Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — Ch. 7 (Sorting), Ch. 8 (Hashing) §7.5
- Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, 3/e — Ch. 2, 6, 7, 8, 11 §2.3
Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.
Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)