ProgrammingVery hardProduct company OA · code-tracing level
What will be the output of the following pseudocode? (Arrays are indexed from 0; / is integer division.)
What will be the output of the following pseudocode? (Arrays are indexed from 0; / is integer division.)
Integer a[7] = {1, 3, 5, 5, 5, 7, 9}, x = 5
Integer lo = 0, hi = 7, mid, steps = 0
while (lo < hi)
mid = (lo + hi) / 2
steps = steps + 1
if (a[mid] < x)
lo = mid + 1
else
hi = mid
end if
end while
Print lo, steps- A. 2 3
- B. 3 3
- C. 2 2
- D. 4 3
Correct answer: A. 2 3
This is a lower-bound search: it finds the first index whose value is ≥ x. Trace: (0, 7) → mid 3, a[3] = 5 ≥ 5, hi = 3; (0, 3) → mid 1, a[1] = 3 < 5, lo = 2; (2, 3) → mid 2, a[2] = 5, hi = 2. lo = hi = 2 after 3 steps. '3 3' assumes the search stops at the first 5 it meets (index 3), as an ordinary binary search would.
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? Integer s = 0 Procedure p(Integer n) if (n == 0) return end if p(n - 1) s = s + n p(n…
- What will be the output of the following pseudocode? (/ is integer division.) Function A(Integer n) if (n <= 0) return 1 end if return B(n…
- What will be the output of the following pseudocode? (g is a global variable.) Integer g = 0 Function f(Integer n) if (n == 0) return 0…
- What will be the output of the following pseudocode? (Integers are passed by value. An array parameter receives a reference to the…
- What will be the output of the following pseudocode? (&& binds more tightly than ||, and both stop evaluating as soon as the result is…
- What will be the output of the following pseudocode? Integer c = 0, i for (i = 1; i <= 50; i = i + 1) i = i 2 c = c + 1 end for Print c, i