4. Identify the bug in this merge function snippet for Merge Sort in Java:
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...
}
medium
A. Array L should be of size n1 + 1
B. Lengths n1 and n2 should be mid - left + 1 and right - mid
C. Copying elements from arr to R should start from mid + 1
D. No bug, code is correct
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 C
Quick Check:
Right half copy starts at mid+1 [OK]
Hint: Right half starts copying from mid+1, not mid [OK]
Common Mistakes:
Starting right half copy at mid instead of mid+1
Incorrect array length calculation
Assuming no overlap in copying
5. Given an array with many duplicate elements, how can you modify Merge Sort to maintain the original order of equal elements (stable sort)?
hard
A. When merging, always pick from the right subarray first
B. Merge Sort cannot be stable with duplicates
C. Use a hash map to track duplicates and reorder after sorting
D. When merging, if elements are equal, pick from the left subarray first
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 D
Quick Check:
Stable merge picks left element first on ties [OK]
Hint: Pick left element first when equal to keep order [OK]
Common Mistakes:
Picking right element first breaks stability
Thinking Merge Sort is unstable by default
Using extra data structures unnecessarily
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.