Binary Search Algorithm
Binary search is an alternative way of searching through a linear set of data. It is much faster than linear search but only works on sorted data, whereas sequential search is for unsorted data. Although sorting takes time, it is (for larger data sets) worth it to sort data and then binary search it than to leave it unsorted and use sequential search. The time complexity of binary search is O(log(n)) because the size of the list is split in half every time it iterates. The way the algorithm works is that it looks at the middle value of a sorted list and checks if it is greater than or less than the value it is searching for. If the middle value is less than the value of what it's searching for, then it splits the list in half and only searches the upper half with the same strategy of splitting. Same goes for if the middle value is greater than the value it's searching for, except with the lower half of the list. Binary search can be either iterative or recursive, but because the recursive version takes up more space O(log(n)), we will implement the iterative version that has a space complexity of O(1).
Below is a C++ implementation of an iterative binary search algorithm: