3. Binary Search
This is a good search algorithm to use IF the list is sorted in some kind of order
For example, the following list is in increasing order:
3,6,9,15,27,34,56,73
Algorithm:
- Let the item to be searched for be T
- Examine the midmost item in the list to see if it is T
- If it was, then it has been found and return its position
- If it is higher than the middle,
- then examine the next one up.
- Adjust the bottom of the list to be this one
- If it not T then examine the next element and adjust the bottom of the list so the list is becoming shorter each time
- Repeat until found or the end of list is reached and return as not found
- If it is lower than the middle
- Examine the next one down and adjust the top of the list to be this item
- If it is not this one, then examine the next lower one and again adjust the top each time
- Repeat until it is found or the beginning of the list is reached and it is not found
Algorithm | Best case | Worst case | Average case | Space complexity |
---|---|---|---|---|
Binary search | O(1) | $O(log_2 \ n)$ | $O(log_2 \ n)$ | $O(1)$ |
The good thing about binary search is that the worst case and average case are the same and so there is a guaranteed maximum number of steps to find an item in the list of length n. And with a space complexity of O(1) it means it can be coded with a fixed amount of storage or memory.
Challenge see if you can find out one extra fact on this topic that we haven't already told you
Click on this link: Coding for binary search