使用java编程给出一序列无序数据:3 56 21 4 78 34 56 34 74,采用顺序查找算法实现查找某个数,请编写程序实现。
时间: 2023-12-10 07:39:15 浏览: 32
可以按照以下步骤来实现顺序查找算法:
1. 定义一个函数,输入参数为要查找的数和待查找的数组;
2. 遍历数组,逐个比较数组中的元素是否等于要查找的数;
3. 如果找到了,则返回该元素在数组中的下标,否则返回-1表示未找到。
以下是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;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {3, 56, 21, 4, 78, 34, 56, 34, 74};
int target = 34;
int index = search(arr, target);
if (index == -1) {
System.out.println("未找到该数");
} else {
System.out.println("该数在数组中的下标为:" + index);
}
}
}
```
输出结果为:该数在数组中的下标为:5(表示要查找的数34在数组中的下标为5)。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)