Data Structures & AlgorithmsModerateTCS NQT · binary search

Problem: What is the number of comparisons needed in the worst case to check whether a sorted array of n elements contains a given value by binary search?

  1. A. n
  2. B. n / 2
  3. C. 1
  4. D. ceil(log2(n + 1))

Correct answer: D. ceil(log2(n + 1))

Each comparison halves the remaining interval, so about log2(n) + 1 comparisons suffice.

More Coding Interview Problems questions

Exams that ask this topic