Merge sort
32 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Merge sort is a classic divide-and-conquer algorithm that guarantees O(n log n) sorting time across all inputs. It recursively divides arrays into halves and merges sorted subarrays.
Divide, sort, and merge
Merge sort splits the array into halves, sorts each half recursively and merges them, always taking O(n log n) time and O(n) extra space.
Merge sort splits the array in half again and again, then merges the sorted halves back together. The program below sorts seven numbers; the diagram traces six.
- If low >= high, return immediately as single-element base case.
- Compute mid = low + (high - low) / 2.
- Recursively call mergeSort(low, mid).
- Recursively call mergeSort(mid + 1, high).
- Call merge(low, mid, high) using temporary buffer.
Merge sort on [38, 27, 43, 3, 9, 82]
Step 1 of 12
- size
- 6
Example 1 · Merging Two Pre-Sorted Arrays in Linear Time
import java.util.Arrays;
public class MergeSortedArraysDemo { public static int[] mergeTwo(int[] a, int[] b) { int[] res = new int[a.length + b.length]; int i = 0, j = 0, k = 0; while (i < a.length && j < b.length) { if (a[i] <= b[j]) res[k++] = a[i++]; else res[k++] = b[j++]; } while (i < a.length) res[k++] = a[i++]; while (j < b.length) res[k++] = b[j++]; return res; }
public static void main(String[] args) { int[] a = {1, 3, 5, 7}; int[] b = {2, 4, 6, 8, 10}; int[] merged = mergeTwo(a, b); System.out.println(Arrays.toString(merged)); }}[1, 2, 3, 4, 5, 6, 7, 8, 10]
What this code does
- Two pointers compare the front of both sorted arrays.
- Smaller item is appended to result array in O(1) step.
- Remaining elements from non-exhausted array are appended sequentially.
Example 2 · Standard Recursive Merge Sort Implementation
import java.util.Arrays;
public class MergeSortDemo { public static void mergeSort(int[] arr) { int[] aux = new int[arr.length]; sort(arr, aux, 0, arr.length - 1); }
private static void sort(int[] arr, int[] aux, int low, int high) { if (low >= high) return; int mid = low + (high - low) / 2; sort(arr, aux, low, mid); sort(arr, aux, mid + 1, high); merge(arr, aux, low, mid, high); }
private static void merge(int[] arr, int[] aux, int low, int mid, int high) { System.arraycopy(arr, low, aux, low, high - low + 1); int i = low, j = mid + 1; for (int k = low; k <= high; k++) { if (i > mid) arr[k] = aux[j++]; else if (j > high) arr[k] = aux[i++]; else if (aux[i] <= aux[j]) arr[k] = aux[i++]; else arr[k] = aux[j++]; } }
public static void main(String[] args) { int[] numbers = {38, 27, 43, 3, 9, 82, 10}; mergeSort(numbers); System.out.println(Arrays.toString(numbers)); }}[3, 9, 10, 27, 38, 43, 82]
What this code does
- Preallocated aux buffer avoids repeated array allocations during recursion.
- System.arraycopy copies current subarray range into buffer.
- Two-pointer merge restores sorted values back into original array.
Example 3 · Bottom-Up Iterative Merge Sort
import java.util.Arrays;
public class IterativeMergeSortDemo { public static void sortBottomUp(int[] arr) { int n = arr.length; int[] aux = new int[n]; for (int width = 1; width < n; width *= 2) { for (int i = 0; i < n - width; i += 2 * width) { int low = i; int mid = i + width - 1; int high = Math.min(i + 2 * width - 1, n - 1); merge(arr, aux, low, mid, high); } } }
private static void merge(int[] arr, int[] aux, int low, int mid, int high) { System.arraycopy(arr, low, aux, low, high - low + 1); int i = low, j = mid + 1; for (int k = low; k <= high; k++) { if (i > mid) arr[k] = aux[j++]; else if (j > high) arr[k] = aux[i++]; else if (aux[i] <= aux[j]) arr[k] = aux[i++]; else arr[k] = aux[j++]; } }
public static void main(String[] args) { int[] arr = {9, 4, 8, 3, 1, 2, 0}; sortBottomUp(arr); System.out.println(Arrays.toString(arr)); }}[0, 1, 2, 3, 4, 8, 9]
What this code does
- Bottom-up merge sort merges subarrays of size 1, then 2, 4, 8.
- It eliminates call stack overhead completely, using O(1) recursion depth.
- Total comparisons remain strictly bounded by O(n log n).
Elementary sorting algorithms slow to quadratic O(n²) time on large datasets. Merge sort breaks through this bottleneck by applying divide-and-conquer recursion. The array is divided into two equal halves until reaching base-case subarrays of size 1. An array of a single element is already sorted by definition. A linear two-pointer merge operation then stitches pairs of sorted subarrays into larger sorted arrays in O(n) time. Consider tracing merge sort on array [38, 27, 43, 3, 9, 82]: Divide into left [38, 27, 43] and right [3, 9, 82]. Recursively sort left into [27, 38, 43] and right into [3, 9, 82]. Merge two sorted halves using two pointers: Compare 27 and 3: take 3. Compare 27 and 9: take 9. Compare 27 and 82: take 27. Compare 38 and 82: take 38. Compare 43 and 82: take 43. Finally copy remaining 82. Resulting merged array is [3, 9, 27, 38, 43, 82]! The merge operation uses two pointer indices tracking the heads of the left and right subarrays. At each step, it copies the smaller element into an auxiliary buffer and advances that pointer. Once one subarray is exhausted, all remaining elements of the other subarray are copied over.
- Divide: find middle index and split array into two halves.
- Conquer: recursively sort left and right halves until base case of size 1.
- Combine: merge two sorted subarrays into one sorted array in O(n) time.
Order of execution
Run merge sort
Tap the steps of mergeSort in order.
Guaranteed O(n log n) time and O(n) space complexity
Unlike quicksort, merge sort guarantees O(n log n) time complexity in the best, average, and worst cases. The recursion tree always divides subarrays in half, producing exactly log₂(n) levels. At each level of the tree, the total merging work across all subarrays requires exactly n operations. Multiplying n operations per level across log₂(n) levels yields strict O(n log n) performance.
The primary trade-off of merge sort is its memory consumption. Merging two subarrays cannot be done in place without shifting elements in O(n²) time. Therefore, merge sort requires an auxiliary array of size O(n) to store merged results. In systems where memory is severely constrained, this extra memory allocation can be prohibitive.
The call stack requires O(log n) stack frames corresponding to the maximum recursion depth. Preallocating a single auxiliary array of size n upfront avoids repetitive heap allocations during recursion.
- Time complexity: O(n log n) in all cases (best, average, and worst).
- Space complexity: O(n) auxiliary memory for buffer array plus O(log n) call stack.
- Buffer optimization: allocate one temp array at the top level and reuse across calls.
Why merge sort is inherently stable
Merge sort is stable because the merge takes the left value when two values are equal. The loop below shows the one comparison that guarantees it.
while (i < left.length && j < right.length) { if (left[i] <= right[j]) out[k++] = left[i++]; // tie: take the LEFT element first else out[k++] = right[j++];}// With < instead of <=, a tie would take the right element first and swap equal keysA sorting algorithm is stable if equal elements retain their original relative order from the input.
Merge sort achieves stability through a single condition inside the merge comparison loop.
When comparing left element a[i] and right element a[j], if they are equal, we choose the left element.
By using left[i] <= right[j] instead of strictly <, the element from the earlier subarray is preserved first.
Because the left subarray originally preceded the right subarray, equal keys never swap positions.
This stability makes merge sort the preferred engine for sorting reference objects in Java.
In fact, Java's standard object sorting algorithm, TimSort, is a hybrid based on merge sort.
Trace stability on equal keys:
Merging left [("A", 1)] and right [("B", 1)]:
Comparison evaluates whether left <= right (1 <= 1 is true).
Left element ("A", 1) is chosen first, followed by ("B", 1).
Result is [("A", 1), ("B", 1)], preserving original order.
- Stability condition: use
<=in merge comparison to prioritize the left subarray on ties. - Object sorting: stability is vital when sorting objects with multiple properties.
- TimSort foundation: Java's TimSort builds upon merge sort to guarantee stable object sorting.
Find the bug
Break the stability
Tap the line that makes the merge unstable.
Equal keys must keep their original order.
Round 1 of 2Next step
Check your understanding
10 quick questions