Merge Sort Method Error
The merge method shown below is intended to merge two sorted subarrays as part of a standard merge sort algorithm. However, the method contains a logical error. Which of the following statements best describes the error and its correction?
public class Sorter {
public static void merge(int[] arr, int low, int mid, int high) {
int n1 = mid - low;
int n2 = high - mid;
int[] left = new int[n1];
int[] right = new int[n2];
for (int i = 0; i < n1; i++) {
left[i] = arr[low + i];
}
for (int j = 0; j < n2; j++) {
right[j] = arr[mid + j];
}
int i = 0, j = 0, k = low;
while(i < n1 && j < n2) {
if(left[i] <= right[j])
arr[k++] = left[i++];
else
arr[k++] = right[j++];
}
while(i < n1)
arr[k++] = left[i++];
while(j < n2)
arr[k++] = right[j++];
}
}
A
The error is in the final while-loop condition, which should check for equality instead of ‘<’.
B
The right subarray size is computed incorrectly; it should be ‘high - mid + 1’.
C
The left subarray size is computed incorrectly; it should be ‘mid - low + 1’ instead of ‘mid - low’.
D
The merge function incorrectly uses index ‘k’ starting at low; it should begin at mid.
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | lsj08030922 | 1 | 1 | 0m 09s | 91 |
| #2 | busemagngr | 1 | 1 | 0m 38s | 62 |
| #3 | cglcndn.11 | 0 | 1 | 0m 02s | -12 |
| #4 | richa.tuli | 1 | 2 | 6m 30s | -300 |
Items per page:
10
1 – 4 of 4
