Quicksort Recursive Call Error
The code below shows an implementation of the quicksort algorithm. The quickSort method, however, contains a logical error that can lead to infinite recursion. Which of the following statements correctly identifies the error?
public class QuickSortOverlap {
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int p = partition(arr, low, high);
quickSort(arr, low, p);
quickSort(arr, p + 1, high);
}
}
public static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if(arr[j] <= pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;
}
}
A
The left recursive call should use ‘quickSort(arr, low, p-1)’ instead of ‘quickSort(arr, low, p)’.
B
The initialization of ‘i’ should be ‘low’ instead of ‘low - 1’.
C
The partition function is incorrectly returning the pivot index.
D
The pivot element should be the first element of the array.
Question Leaderboard
Not enough data yet to show leaderboard.
