| preferred AP College board partner for AP classes
AP Computer Science A/Unit 7: ArrayList
Start Practice TestPractice Test
About Exam
hard Solved by 1 students
Merge Method Loop Assertion
< Prev
Next >

The following merge method is intended to combine two sorted arrays, v and w, into a single sorted array named result.

/** Merges two sorted arrays v and w into a new sorted array result.
* Precondition:
* - v is an array of int sorted in increasing order
* - w is an array of int sorted in increasing order
* - N is the number of elements in array v
* - M is the number of elements in array w
* - v[0]..v[N-1] and w[0]..w[M-1] are initialized with integers.
* - v[0] < v[1] < ... < v[N-1] and w[0] < w[1] < ... < w[M-1]. */

public static int[] merge(int[] v, int[] w, int N, int M) {
    int[] result = new int[N + M];
    int vIndex = 0, wIndex = 0, rIndex = 0;
    while (vIndex < N && wIndex < M) {
        if (v[vIndex] <= w[wIndex]) {
            result[rIndex++] = v[vIndex++];
        } else {
            result[rIndex++] = w[wIndex++];
        }
    }
    while (vIndex < N) {
        result[rIndex++] = v[vIndex++];
    }
    while (wIndex < M) {
        result[rIndex++] = w[wIndex++];
    }
    return result;
}

Which of the following assertions is true at the end of each iteration of the first while loop?

A

result[0..rIndex-1] contains all elements from v and w.

B

All elements in v[0..vIndex-1] and w[0..wIndex-1] have been merged into result[0..rIndex-1] in sorted order.

C

All elements in v[vIndex..N-1] and w[wIndex..M-1] have been merged.

D

No elements have been merged yet.

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: [email protected]|Privacy Policy