Search algorithms
Suppose you are given an array of values and you are required to check whether a particular value is in that array, what is the most natural way to find that element? Well, it seems that the natural way is to go through each element one by one and check whether they match the given value. If any one does, we have found that element and we can return the index; if not, we can return -1
at the end of processing all the elements to report that such an element could not be found. This is what we would call a linear search. The following demonstrates a linear search algorithm in an array:
public static <E, F extends E> int linearSearch(E[] values, valueToLookup) { for (int i = 0; i < values.length; i++) { if (values[i].equals(valueToLookup)) { return i; } } return -1; }
The function linearSearch
takes an array of values and a value to search in it, and returns the index if the value...