Think of an interface as a contract - a class that implements an interface commits to implementing a given list of methods. At has complete freedom on how to do it, and can implement other methods as well. We'll create three classes:
All three classes will implement the Search interface, which has a single method called search.
LinearSearch simply goes through the array from the start and returns the index of the number that you are searching for if it exists in the array, otherwise returns -1.
BinarySearch performs the same functionality, but uses the binary search method, which was covered when we discussed recursion. It assumes the array is sorted; it uses a helper function which receives a range of indices as input, one for the beginning of the range where you are searching for the number, one for the end; it then computes the middle of the range. If the number in the middle of the range is the number you are looking for, great! If not, what do you need to change your range to? When would you stop searching for the number?
RandomSearch is pretty interesting. It just tries five times to locate the number by trying indices randomly. If it doesn't find it in these five attempts, it gives up and says the number is not there. It is recommended that you use a Random object instead of using Math.random()You will need the following files for this part: