Linear Search
If you have a list (or array) that is not sorted, then the simplest searching algorithm is linear search. It goes through the list item by item and compares to the item being searched for. If a comparison succeeds, the algorithm has found the item. If all comparisons fail, the item doesn't exist in the array or list. In the simplest variant, the algorithm returns a boolean to indicate success or failure.
Exercise: Linear Search Consider the list of strings "Cat","Mouse","Frog","Lion","Panda","Llama","Bee", in this order. How many comparisons would it take to find "Panda"? Answer: 5 And how many when searching for "Camel"? Answer: It would take 7 to reach the conclusion the string is not in the list.
Binary Search
If your list is in ascending order, or is put in ascending order by a sorting algorithm, then you can perform a binary search. This involves splitting the data into half at each comparison, thereby 'zooming in' more quickly into the part of the list where the item must be, if it exists in the list. This results in much better performance.
This only took 3 comparisons using binary search, it would have taken 7 using linear search. It gets even better when the list is large. For example, a 1,000,000,000 item list would only take a maximum of 30 comparisons using binary search! It's very useful to have sorted data.
How to work out the maximum number of searches (n) on a x sized array: 2^n > size of list (x) where n = max searches For example, if we had a 3 item array 2^2 = 4 > 3 therefore max searches = 2
|