ProgrammingHardWipro · TCS NQT 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[17] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34}
Integer lo = 0, hi = 16, steps = 0, target = 8
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. 1
- B. 2
- C. 3
- D. 5
Correct answer: B. 2
Binary search on 17 elements halves the range each step. Tracing mid = (lo+hi)/2 at each step until arr[mid] == 8 (at index 3) takes exactly 2 step(s) for this particular target position — not simply ceil(log2(17)) = 5, 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 tightest time complexity of the following pseudocode, in terms of n? (Treat any constant like 2 as a fixed constant, not…
- 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…
- What will be the output of the following pseudocode? (^ is bitwise XOR.) Integer x = 65, y = 72 x = x ^ y y = x ^ y x = x ^ y Print x, y
- This function uses a counter that PERSISTS across calls (a static/global variable), starting at 1. What does each of the 4 calls print, in…
- What will be the output of the following pseudocode? Function isEven(Integer n) if (n == 0) return true end if return isOdd(n - 1) end…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division.) Function f(Integer n, Integer…