Master the divide-and-conquer approach through hands-on implementation of Merge Sort.
Merge Sort is an efficient, stable sorting algorithm that uses a divide-and-conquer strategy. It divides the input array into smaller subarrays, sorts them recursively, and then merges them back together to produce a sorted array.
Implement the recursive divide step
mid = left + (right - left) / 2
prevents integer overflow.Implement the merge step to combine sorted subarrays
Explanation: The divide step takes O(log n) recursive levels, and at each level, the merge operation takes O(n) time, resulting in O(n log n) overall.
Let's visualize how merge sort works with the array [38, 27, 43, 3, 9, 82, 10]:
[38, 27, 43, 3, 9, 82, 10] / \ [38, 27, 43, 3] [9, 82, 10] / \ / \ [38, 27] [43, 3] [9] [82, 10] / \ / \ | / \ [38] [27] [43] [3] [9] [82] [10]
[38] [27] [43] [3] [9] [82] [10] \ / \ / | \ / [27, 38] [3, 43] [9] [10, 82] \ / \ / [3, 27, 38, 43] [9, 10, 82] \ / [3, 9, 10, 27, 38, 43, 82]
Let's zoom in on the merge step for [27, 38] and [3, 43] → [3, 27, 38, 43]:
Left Array | Right Array | Comparison | Result So Far |
---|---|---|---|
[27, 38] | [3, 43] | 27 > 3 | [3] |
[27, 38] | [43] | 27 < 43 | [3, 27] |
[38] | [43] | 38 < 43 | [3, 27, 38] |
[] | [43] | Copy remaining | [3, 27, 38, 43] |
A version that reduces space complexity by merging subarrays in-place:
A non-recursive implementation that uses iteration:
Takes advantage of pre-existing ordered runs in the input array:
Implement the merge sort algorithm to sort an array in ascending order.
public void mergeSort(int[] arr) {
// Your implementation here
// Call mergeSort(arr, 0, arr.length - 1)
}
Implement the merge operation that combines two sorted arrays into a single sorted array.
public int[] merge(int[] arr1, int[] arr2) {
// Your implementation here
// Merge two sorted arrays
}
Modify the merge sort algorithm to sort in descending order.
public void mergeSortDescending(int[] arr) {
// Your implementation here
// Sort array in descending order
}
Hint: Only modify the merge operation to place larger elements first.
Modify the merge sort algorithm to count the number of inversions in an array (pairs of elements that are out of order).
public long countInversions(int[] arr) {
// Your implementation here
// Return the number of inversions in the array
}
Hint: Count inversions during the merge step.
Implement a bottom-up (iterative) version of merge sort without using recursion.
public void iterativeMergeSort(int[] arr) {
// Your implementation here
// Implement merge sort without recursion
}
Hint: Use a loop to merge subarrays of increasing size (1, 2, 4, 8...).