概述
- 依次对数组的元素进行遍历,当数组指定位置元素与要查找的值相等时,返回指定位置即可。
不需要数组有序
实例代码:
private static int linearSearchFirstValue(int[] array, int value) {
if (ObjectUtils.isEmpty(array)) {
throw new RuntimeException("数组为空");
}
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return i;
}
}
return -1;
}
private static int linearSearchLastValue(int[] array, int value) {
if (ObjectUtils.isEmpty(array)) {
throw new RuntimeException("数组为空");
}
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return i;
}
}
return -1;
}
private static List<Integer> linearSearchAllValue(int[] array, int value) {
if (ObjectUtils.isEmpty(array)) {
throw new RuntimeException("数组为空");
}
List<Integer> indexes = Lists.newArrayList();
for (int i = array.length - 1; i >= 0; i--) {
if (array[i] == value) {
indexes.add(i);
}
}
return indexes;
}
public class SearchUtil {
public static void main(String[] args) {
int[] array = {1, 5, 8, 3, 8, 9};
int value = 8;
int index = linearSearchFirstValue(array, value);
System.out.printf("第一个 %d 的位置是:%d\n", value, index);
index = linearSearchLastValue(array, value);
System.out.printf("最后一个 %d 的位置是:%d\n", value, index);
System.out.printf("所有 %d 的位置是:%s\n", value, linearSearchAllValue(array, value).toString());
}
}