线性查找 c语言
时间: 2024-02-14 17:04:22 浏览: 27
线性查找是一种简单的搜索算法,也称为顺序查找。它的实现非常简单,通过依次遍历数组或列表中的元素,直到找到目标元素或者遍历完整个数组或列表为止。以下是一个在 C 语言中实现线性查找的示例代码:
```c
#include <stdio.h>
int linear_search(int arr[], int n, int x) {
int i;
for (i = 0; i < n; i++) {
if (arr[i] == x) {
return i; // 返回目标元素的下标
}
}
return -1; // 目标元素不存在,返回 -1
}
int main() {
int arr[] = {3, 5, 2, 1, 7, 9};
int n = 6;
int x = 7;
int result = linear_search(arr, n, x);
if (result == -1) {
printf("目标元素不存在\n");
} else {
printf("目标元素下标为 %d\n", result);
}
return 0;
}
```
在上面的代码中,我们定义了一个名为 `linear_search` 的函数,它接受一个整型数组 `arr`、数组的大小 `n` 和要查找的目标元素 `x`,并返回目标元素在数组中的下标。如果目标元素不存在,函数返回 -1。
在 `main` 函数中,我们定义了一个整型数组 `arr`,并调用 `linear_search` 函数查找元素 7 的下标。最后,根据函数的返回值输出结果。
需要注意的是,线性查找算法的时间复杂度是 O(n),因此对于大规模数据的查找,建议使用更高效的算法,例如二分查找算法。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)