Merge Method Loop Boundary Error
Consider the following merge method from the MergeSortExample class. The method contains a logic error that results in an ArrayIndexOutOfBoundsException.
public class MergeSortExample {
public static void merge(int[] arr, int low, int mid, int high) {
int n1 = mid - low + 1;
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++) { // Error: should use j < n2
right[j] = arr[mid + 1 + 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++];
}
}
}
Which statement accurately identifies this error?
A
Allocating the left array with size ‘mid - low + 1’ is incorrect.
B
Using ‘j <= n2’ in the second for-loop instead of ‘j < n2’.
C
The recursion base case is missing in this merge sort implementation.
D
The merging while-loop improperly handles remaining elements.
Question Leaderboard
Not enough data yet to show leaderboard.
