Binary Search

Binary Search
Suppose we have an array and want to search an element in it, searching from beginning to end of the array or vice versa will take O(
n)
efficiency.
Binary search is an efficient algorithm for searching an element in a sorted array (or list). It divides the sorted arrayed repeatedly into two parts and narrows down the location of the searched element.
Example: we want to search number 10
in the array [1, 2, 3, 4, 5, 6, 7, 8]
- First, we divide the array into two parts
[1, 2, 3, 4]
and[5, 6, 7, 8]
- We can see numbers
4
and5
are in the middle of the array. Compare10
to4
(left side). - Since
10 > 4
(1), we narrow down the array by continuing to search our number in the second half part[5, 6, 7, 8]
- In the second half part, we repeat the division:
[5, 6]
and[7, 8]
- Now we have
6
, and7
are in the middle. Compare10
to6
(left side again). - Because
10 > 6
(2), we can narrow down the location of searched number in[7, 8]
- We divide the array
[7, 8]
once again into[7]
and[8]
then compare the searched number with[7]
- Compare
10
to7
(3), not match. Compare10
to8
(4), not match either. - Finally, we know the number we want to search for is not in the entire array.
The efficiency of Binary Search:
From (1), (2), (3), and (4) in the example above, we can create a table to count the number of iterations.
Array size | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
---|---|---|---|---|---|---|---|---|---|
Iterations | 0 | 1 | 2 | 2 | 3 | 3 | 3 | 3 | 4 |
From the table, we can see that every time the array is doubled in size, it takes an extra iteration of the algorithm to get through it.
Which means the array size of 1
or 2
0
has 1 iteration (0 + 1). When an array size of 2
or 2
1
has 2 iterations (1 + 1), an array size of 4
or 2
2
has 3 iterations (2 + 1), and an array size of 8
or 2
3
has 4 iterations (3 + 1).
From this observation, we can conclude that efficiency is the exponent of 2 + 1 or O
(log
2
(n) + 1)
:
With approximation, we have the efficiency of Binary Search:
O
(log(n))
A good source to visualize the Binary Search.
Practice from Udacity