Merge Sort Algorithm in DSA Java - Time & Space Complexity
We want to understand how the time taken by merge sort changes as the list size grows.
How does the number of steps grow when sorting bigger lists?
Analyze the time complexity of the following code snippet.
public void mergeSort(int[] arr, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
This code splits the array into halves, sorts each half, then merges them back.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive splitting and merging of subarrays.
- How many times: The array is split into halves repeatedly until single elements, then merged back.
Each split divides the list in half, and merging takes time proportional to the list size at that level.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 40 steps |
| 100 | About 700 steps |
| 1000 | About 10,000 steps |
Pattern observation: Operations grow a bit faster than n but much slower than n squared, roughly n times log n.
Time Complexity: O(n log n)
This means the time grows a little more than linearly as the list gets bigger, thanks to splitting and merging.
[X] Wrong: "Merge sort is as slow as bubble sort because it compares many elements."
[OK] Correct: Merge sort smartly splits the list and merges sorted parts, so it does fewer total comparisons than bubble sort.
Understanding merge sort's time complexity shows you can analyze divide-and-conquer algorithms, a key skill in interviews.
"What if we changed merge sort to split the array into three parts instead of two? How would the time complexity change?"
Practice
Merge Sort algorithm?Solution
Step 1: Understand the divide and conquer approach
Merge Sort splits the array into two halves recursively until single elements remain.Step 2: Merge sorted halves
It then merges these sorted halves to produce a fully sorted array.Final Answer:
Divide the array into halves, sort each half, then merge them -> Option AQuick Check:
Merge Sort = Divide and Conquer [OK]
- Confusing Merge Sort with Bubble Sort
- Thinking it sorts in place without merging
- Believing it picks smallest elements one by one
Solution
Step 1: Identify parameters needed for merging
The merge function needs the array and three indices: left, mid, and right to merge two halves.Step 2: Check return type and parameter order
It returns nothing (void) and parameters match the signature in void merge(int[] arr, int left, int mid, int right).Final Answer:
void merge(int[] arr, int left, int mid, int right) -> Option BQuick Check:
Correct merge signature = void merge(int[] arr, int left, int mid, int right) [OK]
- Using wrong parameter order
- Returning int instead of void
- Missing mid index parameter
{4, 1, 3, 2}?
int[] arr = {4, 1, 3, 2};
mergeSort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));Solution
Step 1: Understand mergeSort on {4,1,3,2}
It splits into {4,1} and {3,2}, sorts each half to {1,4} and {2,3}.Step 2: Merge sorted halves
Merging {1,4} and {2,3} results in fully sorted array {1,2,3,4}.Final Answer:
[1, 2, 3, 4] -> Option AQuick Check:
Sorted array = [1, 2, 3, 4] [OK]
- Confusing merge order
- Not sorting halves before merging
- Printing original unsorted array
void merge(int[] arr, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int[] L = new int[n1];
int[] R = new int[n2];
for (int i = 0; i < n1; i++) L[i] = arr[left + i];
for (int j = 0; j < n2; j++) R[j] = arr[mid + j];
// merging logic follows...
}Solution
Step 1: Check array lengths and copying ranges
Lengths n1 = mid - left + 1 and n2 = right - mid are correct for the left half (left to mid) and right half (mid+1 to right).Step 2: Verify copying elements to R array
Copying to R starts at arr[mid], but it should start at arr[mid + 1] to avoid overlap.Final Answer:
Copying elements from arr to R should start from mid + 1 -> Option CQuick Check:
Right half copy starts at mid+1 [OK]
- Starting right half copy at mid instead of mid+1
- Incorrect array length calculation
- Assuming no overlap in copying
Solution
Step 1: Understand stability in sorting
A stable sort keeps equal elements in their original order.Step 2: Modify merge step for stability
When merging, if elements are equal, always choose the element from the left subarray first to preserve order.Final Answer:
When merging, if elements are equal, pick from the left subarray first -> Option DQuick Check:
Stable merge picks left element first on ties [OK]
- Picking right element first breaks stability
- Thinking Merge Sort is unstable by default
- Using extra data structures unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
