完整代码C语言在一个递增有序的线性表中利用二分查找法查找数据元素X
时间: 2024-03-24 22:40:35 浏览: 24
以下是完整的 C 语言代码实现,在一个递增有序的线性表中利用二分查找法查找数据元素 X:
```c
#include <stdio.h>
int binary_search(int array[], int len, int target) {
int left = 0, right = len - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (array[mid] == target) {
return mid;
} else if (array[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int len = sizeof(array) / sizeof(int);
int target = 5;
int index = binary_search(array, len, target);
if (index != -1) {
printf("Target found at index %d\n", index);
} else {
printf("Target not found\n");
}
return 0;
}
```
这个程序首先定义了一个递增有序的数组 `array`,数组的长度为 `len`,要查找的元素为 `target`。然后调用 `binary_search()` 函数进行查找,将返回值存储在 `index` 变量中。如果返回值不为 -1,则说明目标元素存在于数组中,打印出目标元素的下标。否则,说明目标元素不存在于数组中,打印出提示信息。
在这个程序中,我们调用了 `sizeof()` 函数来获取数组的长度,这是一种常见的获取数组长度的方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)