Background
The binary search algorithm is used to find a value
within an ordered list. The list must be ordered for
this algorithm. The time complexity of this algorithm is
O(log(n)) where n is the number of items in the list.
Altorithm Steps
- Find the midpoint of the array.
- If midpointVal == searchVal, return true
- If not, check if midpointVal is less than or greater than searchVal
- If midpointVal > searchVal, repeat steps 2 and 3 for the left sublist
- If midpointVal < searchVal, repeat steps 2 and 3 for the right sublist
- Repeat this process until searchVal is found, or until there's 1 element
- If the last element doesn't match searchVal, return false
More information
See the image below for an example of the data structure that
could be used for a binary search. The image depicts a list of length
7 that is sorted.
For more information, please reference this link.