Skip to content

Binary Search

Course: Binary search, two sum and strings - chapter 1

Assume you are reading a book, and you want to read Page 747. How can you reach the page?

One way is to go through all the pages one by one till you reach 747. But this will take up a lot of our time.

What we generally do is, open a random page, and check the page number. If the current page number is less than 747, follow the same process on the right side pages. Similarly, if the current page number is greater than 747, check the left side.

Now, in our case, we can be a bit biased while selecting the page to open first during searching. Because we know the page numbers follow a particular order like 1, 2, 3, … and we also know the last page number. So let’s say the total number of pages is 800. So we know 747 is towards the end. So, we will open up a page towards the end of the book in the first iteration.

However, in real life, we do not always have this information. So picking a pivot is crucial for the search to be faster. It has been found that, the search is fastest in worst case when we choose the middle element as the pivot. This leads us to the concept of binary search.

Binary search is a searching algorithm, that works on a monotonic sequence (increasing or decreasing) and efficiently searches for an element.