ProgrammingHardTCS NQT · Accenture

Two sorted arrays a = [1, 4, 7] and b = [2, 3, 8, 9] are merged by the two-pointer procedure below, and the procedure prints the 4th element (1-based) of the merged array. What is printed?

Two sorted arrays a = [1, 4, 7] and b = [2, 3, 8, 9] are merged by the two-pointer procedure below, and the procedure prints the 4th element (1-based) of the merged array. What is printed?
i = 0; j = 0; out = empty
while i < len(a) and j < len(b)
    if a[i] <= b[j] then append a[i]; i++ else append b[j]; j++
append the remaining elements
Print out[3]
  1. A. 3
  2. B. 7
  3. C. 8
  4. D. 4

Correct answer: D. 4

Merged order is 1, 2, 3, 4, 7, 8, 9, so the 4th element is 4. Printing index 2 gives 3, sorting and taking index 4 gives 7, and the 6th element is 8.

More Pseudocode and Code Tracing questions

Exams that ask this topic