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 1 students

Merge Method Loop Boundary Error

Mark
< Prev
Next >

Consider the following merge method from the MergeSortExample class. The method contains a logic error that results in an ArrayIndexOutOfBoundsException.

public class MergeSortExample {
    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++) { // Error: should use j < n2
            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++];
        }
    }
}

Which statement accurately identifies this error?

A

Allocating the left array with size ‘mid - low + 1’ is incorrect.

B

Using ‘j <= n2’ in the second for-loop instead of ‘j < n2’.

C

The recursion base case is missing in this merge sort implementation.

D

The merging while-loop improperly handles remaining elements.

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|