查找算法之线性查找

简介:

线性查找是直接将数组进行遍历,将目标查找出来。方法简单粗暴,效率较低。

代码:

 1     /**
 2      * 线性查找
 3      * @param arr
 4      * @param value 需要查找的值
 5      * @return
 6      */
 7     public static List<Integer> linearSearch(int[] arr, int value) {
 8         if (arr == null || arr.length == 0) {
 9             return Collections.emptyList();
10         }
11         //返回的结果集
12         List<Integer> result = new ArrayList(arr.length);
13         //遍历数组,找到等于value的下标
14         for (int i = 0; i < arr.length; i++) {
15             if (arr[i] == value) {
16                 result.add(i);
17             }
18         }
19         return result;
20     }

 

posted @ 2023-02-02 15:19  Java厨师长  阅读(36)  评论(0)    收藏  举报