Sorting means arranging data in a defined order so that it can be searched, merged and displayed easily. Simple sorts such as bubble or insertion sort need O(n2) time; merge sort is one of the classic algorithms that brings this down to O(n log n) in every case.
How Merge Sort Works
Merge sort is a divide-and-conquer algorithm:
- Divide: split the array into two halves at the middle index.
- Conquer: sort each half recursively. A part with 0 or 1 element is already sorted, which ends the recursion.
- Combine: merge the two sorted halves into one sorted run. Two pointers walk along the halves; at each step the smaller of the two current values is copied to the output.
Dry run for [38, 27, 43, 3]:
split: [38, 27, 43, 3] -> [38, 27] and [43, 3] split: [38, 27] -> [38] [27] [43, 3] -> [43] [3] merge: [38] + [27] -> [27, 38] [43] + [3] -> [3, 43] merge: [27, 38] + [3, 43] -> [3, 27, 38, 43]
Example of Merge Sort in Java
The program uses one helper array, allocated once, for all merges. The middle index is computed as from + (to - from) / 2, which cannot overflow even for very large arrays (unlike (from + to) / 2).
// Merge sort: split the array in half, sort each half, then merge the two sorted halves
public class MergeSortExample {
// Sorts array[from .. to] (both ends inclusive)
static void mergeSort(int[] array, int[] buffer, int from, int to) {
if (from >= to) {
return; // 0 or 1 element: already sorted
}
int mid = from + (to - from) / 2; // avoids int overflow of (from + to)
mergeSort(array, buffer, from, mid);
mergeSort(array, buffer, mid + 1, to);
merge(array, buffer, from, mid, to);
}
// Merges the sorted runs array[from .. mid] and array[mid+1 .. to]
static void merge(int[] array, int[] buffer, int from, int mid, int to) {
for (int k = from; k <= to; k++) {
buffer[k] = array[k]; // copy both runs aside
}
int left = from; // next unused element of the left run
int right = mid + 1; // next unused element of the right run
for (int k = from; k <= to; k++) {
if (left > mid) {
array[k] = buffer[right++]; // left run used up
} else if (right > to) {
array[k] = buffer[left++]; // right run used up
} else if (buffer[right] < buffer[left]) {
array[k] = buffer[right++]; // smaller value comes from the right
} else {
array[k] = buffer[left++]; // ties take the left value: stable
}
}
}
static void sort(int[] array) {
int[] buffer = new int[array.length]; // one shared helper array
mergeSort(array, buffer, 0, array.length - 1);
}
static void printArray(int[] array) {
StringBuilder line = new StringBuilder();
for (int value : array) {
line.append(value).append(' ');
}
System.out.println(line.toString().trim());
}
public static void main(String[] args) {
int[] array = {40, 70, 90, 20, 80, 100, 60, 10, 30, 50};
System.out.println("Original unsorted array is");
printArray(array);
sort(array);
System.out.println();
System.out.println("Sorted array is");
printArray(array);
}
}
Original unsorted array is 40 70 90 20 80 100 60 10 30 50 Sorted array is 10 20 30 40 50 60 70 80 90 100
Time and Space Complexity
| Case | Time | Why |
|---|---|---|
| Best | O(n log n) | The array is always split into log2 n levels, and each level merges n elements. |
| Average | O(n log n) | Same amount of work regardless of the input order. |
| Worst | O(n log n) | Guaranteed; there is no bad input for merge sort. |
Space: O(n) for the helper array, plus O(log n) for the recursion stack. Merge sort is therefore not in place.
Stability: merge sort is stable: when two values are equal, the merge takes the one from the left half first, so equal elements keep their original order.
When to Use Merge Sort
- When a guaranteed O(n log n) running time is required.
- When stability matters, for example when sorting records by one field after another. Java's
Arrays.sort()for objects andCollections.sort()use TimSort, a stable merge-sort variant. - For linked lists and external sorting (data too large for memory), because merging reads data sequentially.
- Avoid it when extra O(n) memory is not available; an in-place algorithm such as heap sort or quick sort is then preferable.