How is the time complexity of binary search logn. It should be n because of number of steps. I am confused.
So according to definition of time complexity its the number of steps so it should be n.Can anyone clarify for me?
Binary search is used on a sorted array. If we define as the size of that array, then the binary search algorithm has a time complexity of O(log).
To analyse this, let's take this iterative pseudo code as provided on Wikipedia:
function binary_search(A, n, T) is
L := 0
R := n − 1
while L ≤ R do
m := floor((L + R) / 2)
if A[m] < T then
L := m + 1
else if A[m] > T then
R := m − 1
else:
return m
return unsuccessful
If we define a step as one iteration of the loop, then there are at most 1+⌊log2⌋ steps. The worst case scenario happens when the target value is not found in . Let's take an example:
A = [2, 4, 6, 8, 10, 12, 14]
n = 7
T = 5
We can follow the state of each variable at the moment m
is assigned its value in each iteration (one row in the table):
iteration | L | R | m | A[m] |
---|---|---|---|---|
1 | 0 | 6 | 3 | 8 |
2 | 0 | 2 | 1 | 4 |
3 | 2 | 2 | 2 | 6 |
After the third iteration the loop exits. So there are 3 iterations. Yet our array has 7 entries, so not every value in the array was inspected. Every iteration the "window" (with and as its boundaries) halves in size. The values in the other half are discarded. So starting with a window of 7 values, this is reduced in one iteration to 3 values, then 1 value, each time halfing the number of potential candidates.