ProgrammingVery hardCapgemini · Infosys pattern
What will be the output of the following pseudocode? (All variables are integers, so / is integer division. Array is sorted and indexed from 0.)
What will be the output of the following pseudocode? (All variables are integers, so / is integer division. Array is sorted and indexed from 0.)
Integer arr[43] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86}
Integer lo = 0, hi = 42, steps = 0, target = 10
while (lo <= hi)
steps = steps + 1
Integer mid = (lo + hi) / 2
if (arr[mid] == target)
Print steps
break
else if (arr[mid] < target)
lo = mid + 1
else
hi = mid - 1
end if
end while- A. 6
- B. 4
- C. 3
- D. 2
Correct answer: C. 3
Binary search on 43 elements halves the range each step. Tracing mid = (lo+hi)/2 at each step until arr[mid] == 10 (at index 4) takes exactly 3 step(s) for this particular target position — not simply ceil(log2(43)) = 6, which is only the worst case.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What is the final content of the stack (bottom to top, left to right) after this sequence of operations on an initially empty stack? push…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division. Array is sorted and indexed…
- What is the final content of the stack (bottom to top, left to right) after this sequence of operations on an initially empty stack? push…
- What is the final content of the queue (front to back, left to right) after this sequence of operations on an initially empty queue?…
- Consider this naive recursive Fibonacci. How many TOTAL calls to fib (including the initial call) happen when computing fib(5)? Function…
- What will be the output of the following pseudocode? (Arrays are passed and assigned BY REFERENCE: b = a makes b point to the same array…