Java查找算法:线性查找
程序员文章站
2022-07-12 10:06:20
...
package com.leolee.dataStructure.search;
import java.util.HashSet;
import java.util.Set;
/**
* @ClassName SeqSearch
* @Description: 线性查找:逐一比对
* @Author LeoLee
* @Date 2020/10/31
* @Version V1.0
**/
public class SeqSearch {
/*
* 功能描述: <br>
* 〈线性查找,查找目标对象,并返回下标〉
* @Param: [arr 查找源, targetValue目标对象]
* @Return: Set 返回目标对象的下标
* @Author: LeoLee
* @Date: 2020/10/31 1:08
*/
public static Set search(int[] arr, int targetValue) {
Set set = new HashSet();
//线性查找,发现有相同的值就返回下标
for (int i = 0; i < arr.length; i++) {
if (arr[i] == targetValue) {
set.add(i);
}
}
return set;
}
public static void main(String[] args) {
int[] arr = {1, 9, 11, -1, 34, 89, 11};//无序数组
SeqSearch.search(arr, 11).forEach(s -> {
System.out.println(s);
});
}
}