实现顺序查找java代码
时间: 2024-06-12 12:09:42 浏览: 5
顺序查找,也称为线性查找,是一种简单的查找算法,顺序地从头到尾遍历待查找的元素,直到找到目标元素或遍历完整个数组。以下是使用Java实现顺序查找的示例代码:
```java
public class SequentialSearch {
public static int sequentialSearch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i; // 找到目标元素,返回索引
}
}
return -1; // 没有找到目标元素,返回-1
}
public static void main(String[] args) {
int[] arr = {5, 3, 8, 2, 9, 1};
int target = 8;
int index = sequentialSearch(arr, target);
if (index != -1) {
System.out.println("目标元素 " + target + " 的索引是 " + index);
} else {
System.out.println("目标元素 " + target + " 不存在");
}
}
}
```
输出结果为:目标元素 8 的索引是 2