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 Solved by 3 students

Merge Sort Recursive Call Error

Mark
< Prev
Next >

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.

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

Question Leaderboard

Rank
User
Correct Count
Attempt Count
Total Time
Score
#1sarah.alyahya90tt11 - 100
#2busemagngr11 0m 22s 78
#3demosolasis111 1m 11s 29
#410818526502 - -20
Items per page:
10
1 – 4 of 4
No comments yet. Be the first to comment!

AI Tutor

How can I help?

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