Hybrid Sort Merge Function Error
The hybridSort method below uses a recursive merge sort approach but switches to insertion sort for small subarrays. An error exists in the merge helper method.
public class HybridSortError {
public static void hybridSort(int[] arr, int low, int high) {
if(high - low < 10) {
// Use insertion sort for small subarrays
for(int i = low + 1; i <= high; i++){
int key = arr[i];
int j = i - 1;
while(j >= low && arr[j] > key) {
arr[j+1] = arr[j];
j--;
}
arr[j+1] = key;
}
} else {
int mid = low + (high - low) / 2;
hybridSort(arr, low, mid);
hybridSort(arr, mid+1, 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+j]; // Error: should be 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 of the following statements accurately identifies the error in the merge method?
A
The recursive calls boundaries in hybridSort are incorrect.
B
The merge function should not merge arrays when the subarray size is below 10.
C
The insertion sort section should start its loop at index ‘low’ instead of ‘low+1’.
D
The second for-loop in merge copies elements from ‘arr[mid+j]’ instead of ‘arr[mid+1+j]’.
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | dormasherpa | 1 | 1 | 0m 38s | 62 |
| #2 | 6test6ing6 | 0 | 1 | - | -10 |
| #3 | znasibli1 | 0 | 1 | - | -10 |
Items per page:
10
1 – 3 of 3
