0

so I'm trying to write a linear search which could be used for most non-primitive data types.

Here is the code I'm using:

public static <T> boolean search(Comparable<T> key, T[] array) {
    for(int i = 0; i < array.length; i++) {
        if(array[i].equals(key)) {
            return true;
        }
    }
    return false;
}

I was wondering if there is a better way this could be done, or a neater way. N.B. I am just looking to use a linear search algorithm

Thanks

madcrazydrumma
  • 1,847
  • 3
  • 20
  • 38

2 Answers2

1

You could use List#contains for a linear search. Also, there's no need for Comparable in this case.

public static <T> boolean search(T needle, T[] haystack) {
    return Arrays.asList(haystack).contains(needle);
}

Note: Arrays.asList returns a List view of the array. It won't make a copy.

4castle
  • 32,613
  • 11
  • 69
  • 106
-3

Binary search works amazing! And it's quite simple.

public static <T> boolean search(Comparable<T> key, T[] array) {
    int start = 0;
    int end = array.length - 1;
    while (start <= end) {
        int mid = (start + end) / 2;
        if (key == array[mid]) {
            return true;
        }
        if (key < array[mid]) {
            end = mid - 1;
        } else {
            start = mid + 1;
        }
    }
    return false;
}
Michael
  • 776
  • 4
  • 19