How come the time complexity of Binary Search is log n

Here's an answer to the question

How come the time complexity of Binary Search is $\log n$?

that describes informally what's going on in the binary tree in the question and in the video (which I have not watched).

You want to know how long binary search will take on input of size $n$, as a function of $n$.

At each stage of the search (pass through the body of the while loop) you split the input in half, so you successively reduce the size of the problem (h-l) this way: $$ n, n/2, n/4, n/8 \ldots . $$ (Strictly speaking, you round those to integers.)

Clearly you will be done when the input is $1$, for there's just one place. That index is the answer.

So you want the number of steps $k$ such that $n/2^k \le 1$. That's the smallest $k$ for which $2^k \ge n$. The definition of the logarithm says that $k$ is about $\log_2(n)$, so binary search has that complexity.

Tags:

Algorithms