Binary search

Binary search is a very popular search algorithm in the programming world. In sequential search, we started from the beginning and scanned through each item to find the desired one. However, if the list is already sorted, then we do not need to search from the beginning or the end of the list. In a binary search algorithm, we start with the middle of the list, check whether the item in the middle is smaller or greater than the item we are looking for, and decide which way to go. This way, we divide the list by half and discard one half completely, just like the following image:

If we look at the preceding image, we have a sorted ...

Get PHP 7 Data Structures and Algorithms now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.