Merge Sort is a powerful, efficient, and stable sorting algorithm that uses the divide and conquer paradigm. It is especially effective for large datasets and is often preferred when predictable performance and stability are required.
Merge Sort follows three key steps:
This process continues recursively until the array is broken down into subarrays of size 1 (which are inherently sorted), and then merged step-by-step into a sorted array.
| Case | Time Complexity |
|---|---|
| Best | O(n log n) |
| Average | O(n log n) |
| Worst | O(n log n) |
public class MergeSortExample {
public static void mergeSort(int[] array) {
if (array.length < 2) return;
int mid = array.length / 2;
int[] left = new int[mid];
int[] right = new int[array.length - mid];
// Split array into left and right halves
for (int i = 0; i < mid; i++) {
left[i] = array[i];
}
for (int i = mid; i < array.length; i++) {
right[i - mid] = array[i];
}
// Recursive sort
mergeSort(left);
mergeSort(right);
// Merge the sorted halves
merge(array, left, right);
}
public static void merge(int[] array, int[] left, int[] right) {
int i = 0, j = 0, k = 0;
// Merge elements into original array
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
array[k++] = left[i++];
} else {
array[k++] = right[j++];
}
}
// Copy remaining elements
while (i < left.length) {
array[k++] = left[i++];
}
while (j < right.length) {
array[k++] = right[j++];
}
}
public static void printArray(int[] array) {
for (int value : array) {
System.out.print(value + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {38, 27, 43, 3, 9, 82, 10};
System.out.println("Original array:");
printArray(arr);
mergeSort(arr);
System.out.println("Sorted array:");
printArray(arr);
}
}
Original array:
38 27 43 3 9 82 10
Sorted array:
3 9 10 27 38 43 82
Let’s walk through sorting the array:[38, 27, 43, 3, 9, 82, 10]
We recursively divide the array:
[38, 27, 43, 3, 9, 82, 10]
→ [38, 27, 43] and [3, 9, 82, 10]
→ [38], [27, 43] and [3, 9], [82, 10]
→ [38], [27], [43], [3], [9], [82], [10]
Start merging sorted individual elements:
[27], [43] → [27, 43]
[27, 43], [38] → [27, 38, 43]
[3], [9] → [3, 9]
[82], [10] → [10, 82]
[3, 9], [10, 82] → [3, 9, 10, 82]
Merge the two major sorted halves:
[27, 38, 43], [3, 9, 10, 82]
→ [3, 9, 10, 27, 38, 43, 82]
[3, 9, 10, 27, 38, 43, 82]