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 Method Error

Mark
< Prev
Next >

The merge method shown below is intended to merge two sorted subarrays as part of a standard merge sort algorithm. However, the method contains a logical error. Which of the following statements best describes the error and its correction?

public class Sorter {
    public static void merge(int[] arr, int low, int mid, int high) {
        int n1 = mid - low;
        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 + 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 error is in the final while-loop condition, which should check for equality instead of ‘<’.

B

The right subarray size is computed incorrectly; it should be ‘high - mid + 1’.

C

The left subarray size is computed incorrectly; it should be ‘mid - low + 1’ instead of ‘mid - low’.

D

The merge function incorrectly uses index ‘k’ starting at low; it should begin at mid.

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
#1lsj0803092211 0m 09s 91
#2busemagngr11 0m 38s 62
#3cglcndn.1101 0m 02s -12
#4richa.tuli12 6m 30s -300
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|