X1529: Rewrite Linear Search with Generics

The code below is a linear search looking for an integer (search) in an array of integers (numbers). It returns the index of the position where search is found, or -1 if it is not found.

public int linearSearch(int[] numbers, int search)
{
   for (int i = 0; i < numbers.length; i++) {
      if (numbers[i] ==  search)
         return i;
   }
   return -1;  // not found
}

Rewrite the linearSearch using generic parameter E. The type of E extends a Comparable, that is it has the method compareTo() defined. Here is the definition without the code that you will write below.

public class Search<E extends Comparable<E>>
{
   public int linearSearch(E[] items, E search)
   {
      your code
   }
}

You may consult the String documentation for other methods to use.

You may consult the Comparable documentation for other methods to use.

Examples:

test({14,15,10,11,12,13,16}, 1) -> -1
test({"hello", "world"}, "hello") -> 0

Your Answer:

Feedback

Your feedback will appear here when you check your answer.