The time complexity of binary search is as follows:
- Worst-case complexity: O(logn)O(\log n)O(logn)
This occurs when the target element is located at the extremities (either the smallest or largest element) of the sorted array or when the element is not present at all. In this case, the algorithm repeatedly halves the search space until only one element remains to be checked, resulting in about log2n\log_2 nlog2n comparisons
- Average-case complexity: O(logn)O(\log n)O(logn)
On average, assuming the target element is equally likely to be at any position or absent, the number of comparisons is also proportional to logn\log nlogn. The average number of comparisons is slightly less than the worst case but still dominated by logn\log nlogn
Additionally, the best-case complexity is O(1)O(1)O(1), which happens if the target element is found at the middle of the array on the first comparison.
Summary
Case| Time Complexity
---|---
Best Case| O(1)O(1)O(1)
Average Case| O(logn)O(\log n)O(logn)
Worst Case| O(logn)O(\log n)O(logn)
The space complexity depends on the implementation:
- Iterative binary search uses constant space: O(1)O(1)O(1).
- Recursive binary search uses space proportional to the recursion depth: O(logn)O(\log n)O(logn)
Thus, binary search is efficient for searching in sorted arrays due to its logarithmic time complexity in both average and worst cases.