US Trends

what are the worst case and average case complexity of a binary search

The worst case and the average case time complexity of a binary search are both O(log⁡n)O(\log n)O(logn).

Quick Scoop: Binary Search Complexities

1. Direct Answer

  • Worst-case time complexity : O(log⁡n)O(\log n)O(logn)
  • Average-case time complexity : O(log⁡n)O(\log n)O(logn)
  • (For completeness, best case is O(1)O(1)O(1) when the element is found in the first comparison.)

2. Why worst case is O(log⁡n)O(\log n)O(logn)

Binary search works by repeatedly cutting the search space in half: compare the middle element, then discard either the left or right half.

  • Start with nnn elements.
  • After 1 comparison: about n/2n/2n/2 remain.
  • After 2 comparisons: about n/4n/4n/4 remain.
  • After kkk comparisons: about n/2kn/2^kn/2k remain.

You stop when the remaining part is of size 1, i.e. when n/2k≈1n/2^k\approx 1n/2k≈1, which gives 2k≈n2^k\approx n2k≈n and so k≈log⁡2nk\approx \log_2 nk≈log2​n.

This log⁡n\log nlogn number of steps bounds the worst case , such as when the element is at an extreme end or not present at all.

3. Why average case is also O(log⁡n)O(\log n)O(logn)

If every position (and also “not found”) is equally likely for the target, the expected number of comparisons is just slightly less than the worst case, but still proportional to log⁡n\log nlogn.

  • A detailed calculation gives an average comparisons term like Nlog⁡NN+1\frac{N\log N}{N+1}N+1NlogN​, whose dominant part is proportional to log⁡N\log NlogN.
  • In asymptotic notation, we ignore constants and lower-order terms, so the average-case complexity is also O(log⁡n)O(\log n)O(logn).

4. Intuitive mini-story

Imagine a phonebook with names in alphabetical order.

  • Each time you open it, you flip to the middle name and decide: is your name before or after this page?
  • You then throw away half the book mentally and repeat.
  • Even if your name is very early or very late (worst case) or somewhere in the middle (average case), the number of page checks grows very slowly with the size of the book—logarithmically.

5. SEO-style recap (for your post)

  • Focus keyword: what are the worst case and average case complexity of a binary search
  • Core fact: both worst and average case are O(log⁡n)O(\log n)O(logn) for a standard binary search on a sorted array.
  • Context: This makes binary search far more scalable than linear search O(n)O(n)O(n), especially for large sorted datasets.

TL;DR:
For binary search on a sorted array of size nnn, both the worst-case and average-case time complexity are O(log⁡n)O(\log n)O(logn), thanks to halving the search space on every step.

Information gathered from public forums or data available on the internet and portrayed here.