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
easy Solved by 1 students

Hybrid Sort Merge Function Error

Mark
< Prev
Next >

The hybridSort method below uses a recursive merge sort approach but switches to insertion sort for small subarrays. An error exists in the merge helper method.

public class HybridSortError {
    public static void hybridSort(int[] arr, int low, int high) {
        if(high - low < 10) {
            // Use insertion sort for small subarrays
            for(int i = low + 1; i <= high; i++){
                int key = arr[i];
                int j = i - 1;
                while(j >= low && arr[j] > key) {
                    arr[j+1] = arr[j];
                    j--;
                }
                arr[j+1] = key;
            }
        } else {
            int mid = low + (high - low) / 2;
            hybridSort(arr, low, mid);
            hybridSort(arr, mid+1, 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+j]; // Error: should be 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 of the following statements accurately identifies the error in the merge method?

A

The recursive calls boundaries in hybridSort are incorrect.

B

The merge function should not merge arrays when the subarray size is below 10.

C

The insertion sort section should start its loop at index ‘low’ instead of ‘low+1’.

D

The second for-loop in merge copies elements from ‘arr[mid+j]’ instead of ‘arr[mid+1+j]’.

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
#1dormasherpa11 0m 38s 62
#26test6ing601 - -10
#3znasibli101 - -10
Items per page:
10
1 – 3 of 3
No comments yet. Be the first to comment!

AI Tutor

How can I help?

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