ProgrammingHardAmazon OA · Goldman Sachs OA
What will be the output of the following pseudocode? (All variables are integers, so / is integer division; arrays are indexed from 0)
What will be the output of the following pseudocode? (All variables are integers, so / is integer division; arrays are indexed from 0)
Integer a[6] = {1, 3, 8, 12, 4, 2}
Integer lo = 0, hi = 5, mid, steps = 0
while (lo < hi)
mid = (lo + hi) / 2
if (a[mid] < a[mid + 1])
lo = mid + 1
else
hi = mid
end if
steps = steps + 1
end while
Print lo, a[lo], steps- A. 3 12 3
- B. 3 12 2
- C. 2 8 3
- D. 4 4 3
Correct answer: A. 3 12 3
This binary search climbs towards a peak. mid = 2: 8 < 12, lo = 3; mid = 4: 4 > 2, hi = 4; mid = 3: 12 > 4, hi = 3. Stops after 3 steps at index 3: 3 12 3.
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? Stack s1 = empty, s2 = empty Procedure enqueue(Integer x) push(s1, x) End Procedure…
- What will be the output of the following pseudocode? (^ is bitwise XOR) Integer s = 0 for (each i from 0 to 15) s = s + (i ^ 5) end for…
- What will be the output of the following pseudocode? (parameters are passed by value; inside g, x is the global x; operands are evaluated…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division; + joins strings) Function…
- What is the time complexity of the following pseudocode, as a function of n? i = n while (i > 1) j = i while (j < n) j = j 2 end while i =…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer c = 0, i = 1, j while…