Back

How Binary Searches Work

The binary search algorithm is often more efficient than the linear search - however, the list must be sorted beforehand. Therefore, the inputs are a list sorted into ascending order and a target item. The binary search compares the target item with the item in the middle of the sorted list. If the target item is smaller, the search focuses only on the left side of the list, where numbers smaller than the middle value are found. If it is larger, it focuses on the right. If they are the same, then the search stops as the item has been found. Using this process continuously, the size of the list being searched halves each time until the search item is found.

A simple way to remember this search is to think of searching a dictionary. When searching for a specific word, it is infeasible to check every page. First, you could check the middle of the book. If the word is alphabetically before the words on this page, you now only need to search the first half of the dictionary. This halving process can be repeated until the item is found.

The best case is when the search item is in the middle of the list. This results in O(1) time complexity as no further splitting is required. In the worst case, where the item is not present, and in the average case, the time complexity is O(logn). This is because the size of the list being searched halves every time until the item is found.