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- A. 5
- B. 4
- C. 6
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? (Arrays are indexed from 0.) Integer m[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division.) Integer c = 0, i = 16 while…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division.) Function f(Integer n) if (n <…
- How many lines does this pseudocode print for hanoi(5, 'A', 'B', 'C')? Function hanoi(Integer n, Char from, Char via, Char to) if (n == 0)…
- How many of the following pseudocode statements print 1? (/ is integer division; & is bitwise AND; ^ is bitwise XOR.) (i) Print (7 / 2) 2…
- What will be the output of the following pseudocode? Integer a = 12, b = 18, t while (b != 0) t = b b = a mod b a = t end while Print a