QuickSort Infinite Recursion Error
The following quickSort implementation contains a flaw that can cause infinite recursion. Which of the following changes corrects this error?
public class QuickSortInfinite {
public static void quickSort(int[] arr, int low, int high) {
if(low < high) {
int p = partition(arr, low, high);
quickSort(arr, low, p); // Error: may cause infinite recursion if p == low
quickSort(arr, p + 1, high);
}
}
public static int partition(int[] arr, int low, int high) {
int pivot = arr[low];
int i = low, j = high;
while(i < j) {
while(i < high && arr[i] <= pivot) i++;
while(arr[j] > pivot) j--;
if(i < j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[low];
arr[low] = arr[j];
arr[j] = temp;
return j;
}
}
A
Add a check to exit if p equals low.
B
Replace the call quickSort(arr, low, p) with quickSort(arr, low, p-1) to avoid including the pivot repeatedly.
C
Remove the left recursive call entirely.
D
Change the pivot selection from arr[low] to arr[high].
Question Leaderboard
Not enough data yet to show leaderboard.
