ProgrammingHardTCS NQT · Accenture pattern

What is the time complexity of binary search on a sorted array of n elements?

What is the time complexity of binary search on a sorted array of n elements?
Function binarySearch(Array arr, Integer target)
    Integer lo = 0, hi = length(arr) - 1
    while (lo <= hi)
        Integer mid = (lo + hi) / 2
        if (arr[mid] == target)
            return mid
        else if (arr[mid] < target)
            lo = mid + 1
        else
            hi = mid - 1
        end if
    end while
    return -1
End Function
  1. A. O(n)
  2. B. O(n^2)
  3. C. O(log n)
  4. D. O(1)

Correct answer: C. O(log n)

Each iteration discards half of the remaining search range, so the number of iterations needed to shrink n elements down to 0 or 1 is O(log n).

More Pseudocode and Code Tracing questions

Exams that ask this topic