Complexity Analysis
Let's discuss how fast binary search is and how much memory it uses.
We'll cover the following...
What will be the space complexity for binary search in terms of Big O notation?
O(log_2 \space n)
O(2 ^ n)
O(1)
O(n ^ 2)
What will be the time complexity for binary search in terms of Big O notation?
O(log_2 \space n)
O(2 ^ n)
O(n)
O(n ^ 2)
Time complexity
The essential property of binary search is to reduce the search area to, nearly, half of the original size.
Suppose we have n` elements in our search array. On each iteration, we’re down to ​ 2n elements. The search area keeps halving from n to ​2​n, to 4​n, to 8n, and so on, until the area becomes of size 1 (unless we found the target in some previous step).
At this point, we either find the value or prove that it doesn’t exist in the search array.
The total runtime is then a matter of how many steps (dividing n by 2
each time) we can take until n becomes 1
.
Here is a visual representation of our algorithm for the worst cases:
- When the target is the first element in the array:
- When the target is the last element in the array:
There are elements in our array. To find the number of times we have ...