Choosing how to earn college credit? CLEP vs AP guide
| preferred AP College board partner for AP classes
AP Computer Science A/Unit 4: Data Collections
Start Practice TestPractice Test
About Exam
medium

QuickSort Infinite Recursion Error

Mark
< Prev
Next >

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].

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer
Report Question

Question Leaderboard

Not enough data yet to show leaderboard.

No comments yet. Be the first to comment!

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Instagram: @_apfive_|Privacy Policy|