ProgrammingHardAccenture · Cognizant pattern

Two sorted arrays a = {1, 4, 7} and b = {2, 3, 8, 9} are merged. How many element comparisons does the pseudocode make?

Two sorted arrays a = {1, 4, 7} and b = {2, 3, 8, 9} are merged. How many element comparisons does the pseudocode make?
Integer i = 0, j = 0, comp = 0
while (i < 3 && j < 4)
    comp = comp + 1
    if (a[i] <= b[j])
        i = i + 1
    else
        j = j + 1
    end if
end while
Print comp
  1. A. 5
  2. B. 4
  3. C. 6
  4. D. 7

Correct answer: A. 5

The comparisons are 1 vs 2, 4 vs 2, 4 vs 3, 4 vs 8, 7 vs 8. After that a is used up and 8, 9 are copied without comparing. That is 5. The worst case of m + n - 1 = 6 is the trap.

More Pseudocode and Code Tracing questions

Exams that ask this topic