搜索-線性搜索

線性搜索是最簡單的搜索算法,通常稱爲順序搜索。 在這種類型的搜索中,只是完全遍歷列表,並將列表中的每個元素與要找到其位置的項匹配。如果找到匹配,則返回項目的位置,否則算法返回NULL。
public class LineSearch {
    public static void main(String[] args) {
        int[] arr = {10, 23, 15, 8, 4, 3, 25, 30, 34, 2, 19};
        int item = 34;
        int pos = lineSearch(arr, item);
        if (pos != -1) {
            System.out.println("Item found at location " + pos);
        } else
            System.out.println("Item not found");

    }

    private static int lineSearch(int[] data, int searchItem) {
        for (int i = 0, n = data.length; i < n; i++) {
            if (data[i] == searchItem) {
                return i;
            }
        }
        return -1;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章