Think of an interface as a contract: a class that implements an interface commits to implementing a given list of methods. It 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 Searching interface, which has a single method called search.
LinearSearch simply goes through the array from the start and returns the index of the first occurrence of the number that you are searching for if it exists in the array, otherwise returns -1.
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(). The random object will pick a number in the given range every time it is called and therefore it will occasionally guess the same number more than once. For an extra challenge, can you keep your random method from guessing the same number twice?
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?
You will need the following files for this part: