An algorithm for sorting a list of numbers on paper could be:
- Compare item to list[middle]. If item = list[middle], then we have found it. If item < list[middle], then look in the first half of the list. If item > list[middle], then look in the second half of the list.
- Redefine list to be the half of the list where we continue our search and repeat the first step.
- Stop when we have found the item or know it is missing. We know it is missing when there is nowhere else to look and we still haven't found it.
Average number of iterations on a sorted list:
Length of List Sequential Search Binary Search
10 5.5 2.9
100 50.5 5.8
1,000 500.5 9.0
10,000 5000.5 12.4
Which search algorithm to use? Depends on the situation. There are basically three factors to keep in mind when deciding on an algorithm:
- The length of the list to be searched
- Whether or not the list is already sorted
- The number of times the list is to be searched
A graphical view of this binary search method is
here.