ProgrammingVery hardTCS NQT · Accenture

Sorted array a = [1, 3, 6, 6, 6, 9]. The lower-bound binary search below finds the first index whose value is at least x = 6. What is printed?

Sorted array a = [1, 3, 6, 6, 6, 9]. The lower-bound binary search below finds the first index whose value is at least x = 6. What is printed?
lo = 0; hi = n
while lo < hi
    mid = (lo + hi) div 2
    if a[mid] < x then lo = mid + 1 else hi = mid
end while
Print lo
  1. A. 5
  2. B. 3
  3. C. 1
  4. D. 2

Correct answer: D. 2

The first 6 is at index 2, which is the lower bound. Using <= moves past all the 6s and gives the upper bound 5, counting the 6s gives 3, and a broken hi update returns 1.

More Pseudocode and Code Tracing questions

Exams that ask this topic