ProgrammingHardAccenture · Cognizant pattern

What will be the output of the following pseudocode (merging two sorted arrays)? (Arrays are indexed from 0.)

What will be the output of the following pseudocode (merging two sorted arrays)? (Arrays are indexed from 0.)
Integer a[4] = {1, 3, 5, 7}
Integer b[5] = {2, 4, 6, 8, 10}
Integer i = 0, j = 0
List merged = empty list
while (i < length(a) and j < length(b))
    if (a[i] < b[j])
        append(merged, a[i])
        i = i + 1
    else
        append(merged, b[j])
        j = j + 1
    end if
end while
append remaining elements of a (from i) and b (from j) to merged
Print merged
  1. A. [1, 2, 3, 4, 5, 6, 7, 8, 10]
  2. B. [1, 2, 3, 4, 5, 6, 7, 10, 8]
  3. C. [2, 1, 4, 3, 6, 5, 8, 7, 10]
  4. D. [1, 3, 5, 7, 2, 4, 6, 8, 10]

Correct answer: A. [1, 2, 3, 4, 5, 6, 7, 8, 10]

This is the standard merge step of merge sort: comparing the fronts of both sorted arrays and taking the smaller each time correctly interleaves them into one fully sorted array, then appends the leftover tail of b once a is exhausted.

More Pseudocode and Code Tracing questions

Exams that ask this topic