A binary search locates an item in a sorted array by repeatedly dividing the search interval in half.
How do you search a name in a telephone directory?
One way would be to start from the first page and look at each name in the phonebook till we find what we are looking for. But that would be an extremely laborious and inefficient way to search.
Because we know that names in the phonebook are sorted alphabetically, we could probably work along the following steps:
1. Open the middle page of the phonebook
2. If it has the name we are looking for, we are done!
3. Otherwise, throw away the half of the phonebook that does not contain the name
4. Repeat until you find the name or there are no more pages left in the phonebook
Time complexity: As we dispose off one part of the search case during every step of binary search, and perform the search operation on the other half, this results in a worst case time complexity of *O*(*log<sub>2</sub>N*).
In detail, how many times can you divide N by 2 until you have 1? This is essentially saying, do a binary search (half the elements) until you found it. In a formula this would be this:
```
1 = N / 2x
```
Multiply by 2x:
```
2x = N
```
Now do the log2:
```
log2(2x) = log2 N
x * log2(2) = log2 N
x * 1 = log2 N
```
This means you can divide log N times until you have everything divided. Which means you have to divide log N ("do the binary search step") until you found your element.
*O*(*log<sub>2</sub>N*) is such so because at every step half of the elements in the data set are gone which is justified by the base of the logarithmic function.
The middle element is the item we were looking for!
The binary search algorithm takes a divide-and-conquer approach where the array is continuously divided until the item is found or until there are no more elements left for checking. Hence, this algorithm can be defined recursively to generate an elegant solution.
Binary Search Trees are very powerful because of their O(log n) search times, second to the hashmap data structure which uses a hashing key to search for data in O(1). It is important to understand how the log n run time comes from the height of a binary search tree. If each node splits into two nodes, (binary), then the depth of the tree is log n (base 2).. In order to improve this speed in Data System, we use B+ trees because they have a larger branching factor, and therefore more height. I hope this short article helps expand your mind about how binary search is used in practical systems.