Merge Sort Recursive Call Error
The mergeSort method in the MergeSort class below is intended to sort an array of integers but contains a logical error. Which statement accurately describes the error related to the recursive calls?
public class MergeSort {
public static void mergeSort(int[] arr, int low, int high) {
if(low < high) {
int mid = (low + high) / 2;
mergeSort(arr, low, mid);
mergeSort(arr, mid, high);
merge(arr, low, mid, high);
}
}
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++) {
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++];
}
}
A
The second recursive call should be mergeSort(arr, mid+1, high) instead of mergeSort(arr, mid, high).
B
A base case for an empty array is missing.
C
The error is in the merge method where the arrays are merged incorrectly.
D
The error lies in the calculation of mid; it should be low + (high - low) / 2.
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | sarah.alyahya90tt | 1 | 1 | - | 100 |
| #2 | busemagngr | 1 | 1 | 0m 22s | 78 |
| #3 | demosolasis1 | 1 | 1 | 1m 11s | 29 |
| #4 | 108185265 | 0 | 2 | - | -20 |
Items per page:
10
1 – 4 of 4
