0

所以我正在尝试编写一个可用于大多数非原始数据类型的线性搜索。

这是我正在使用的代码:

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;
}

我想知道是否有更好的方法可以做到这一点,或者更整洁的方法。注意我只是想使用线性搜索算法

谢谢

4

2 回答 2

1

您可以List#contains用于线性搜索。Comparable此外,在这种情况下也不需要。

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

注意:Arrays.asList返回List数组的视图。它不会复制。

于 2016-07-02T23:59:10.120 回答
-3

二进制搜索效果惊人!这很简单。

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;
}
于 2016-07-02T23:38:03.860 回答