binary search takes (given a sorted list) the middle element and checks if this what you are looking for is bigger or not and then checking only the right or the left half for the element you are looking for. In a sortet list you know: if an element is to big, everything at the right of this element is also to big.
You can see the log n
complexity this way:
Writing down a balanced binary tree starting with the middle element of the list. the two children are the middle values of the right and the left sublists.
Now the number of leafs in your tree doubles every step. your binary search starts at the root and desides every step to go left or right. The worst case is, that the element you are looking for is not in the list, so if you reach a leaf and it has not the right value, the element is not in the list.
But how many steps your search do? just as many as the depth of your tree. Let this number x
. It holds
2x-1 < n ≤ 2x => x = ceil( log n )
As big O describes an upper bound you can say binary search runs in O(log n)
.
O(log n)
means that you can always find a constant number c
such that the steps of the algorithm holds steps < c ⋅ log n
.
Side note: if steps < c ⋅ log n
holds, then also steps < c ⋅ n
so binary search is also in O(n)
, but O(n)
is not close. Instead of O(log n) you can say Θ(log n), which means it taks log n
steps, not more not less (except for a constant factor)