用java实现(1)给出一序列无序数据:3 56 21 4 78 34 56 34 74,采用顺序查找算法实现查找某个 数,请编写程序实现。
时间: 2023-12-10 20:41:47 浏览: 38
以下是使用Java实现顺序查找算法查找某个数的示例代码:
```java
public class SequentialSearch {
public static int search(int[] arr, int target) {
// 遍历数组,查找目标数
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i;
}
}
// 如果未找到目标数,返回-1
return -1;
}
public static void main(String[] args) {
int[] arr = {3, 56, 21, 4, 78, 34, 56, 34, 74};
int target = 78;
int index = search(arr, target);
if (index != -1) {
System.out.println("目标数" + target + "在数组中的位置为:" + index);
} else {
System.out.println("目标数" + target + "未在数组中找到!");
}
}
}
```
程序输出:
```
目标数78在数组中的位置为:4
```
上述代码中,`search`方法接收一个整数数组和一个目标数作为参数,使用顺序查找算法遍历整个数组,查找目标数,并返回目标数在数组中的下标,如果未找到目标数,返回-1。在`main`方法中,定义一个整数数组`arr`和目标数`target`,然后调用`search`方法查找目标数在数组中的位置,并输出结果。