ProgrammingHardAccenture · Cognizant

Array a = [2, 5, 7, 10, 12] is searched for the number of elements less than or equal to 7 by a binary search that finds the boundary index (the first index whose value is greater than 7). What is the index printed?

Array a = [2, 5, 7, 10, 12] is searched for the number of elements less than or equal to 7 by a binary search that finds the boundary index (the first index whose value is greater than 7). What is the index printed?
lo = 0; hi = n
while lo < hi
    mid = (lo + hi) div 2
    if a[mid] <= 7 then lo = mid + 1 else hi = mid
end while
Print lo
  1. A. 2
  2. B. 4
  3. C. 5
  4. D. 3

Correct answer: D. 3

Values up to 7 are 2, 5, 7 so the first index with a larger value is 3. Using a strict test returns 2, counting the values up to 7 and adding one gives 4, and the array length 5 is a different number.

More Pseudocode and Code Tracing questions

Exams that ask this topic