用c语言编写一个程序,实现对有序数组的折半查找算法。
时间: 2024-03-01 14:52:18 浏览: 32
好的,以下是一个简单的 C 语言程序,用于实现对有序数组的折半查找算法:
```c
#include <stdio.h>
// 二分查找函数
int binarySearch(int arr[], int len, int target)
{
int left = 0; // 左侧边界
int right = len - 1; // 右侧边界
while (left <= right)
{
int mid = (left + right) / 2; // 中间位置
if (arr[mid] == target)
{
return mid; // 找到目标元素,返回下标
}
else if (arr[mid] < target)
{
left = mid + 1; // 目标元素在右半部分,缩小左侧边界
}
else
{
right = mid - 1; // 目标元素在左半部分,缩小右侧边界
}
}
return -1; // 未找到目标元素,返回 -1
}
int main()
{
int arr[10] = {2, 5, 8, 10, 15, 20, 25, 30, 35, 40}; // 假设要查找的数组为 arr,数组长度为 10
int target = 15; // 假设要查找的目标元素为 15
// 二分查找
int index = binarySearch(arr, 10, target);
// 输出查找结果
if (index != -1)
{
printf("找到了目标元素 %d,它在数组中的下标为 %d。\n", target, index);
}
else
{
printf("未找到目标元素 %d。\n", target);
}
return 0;
}
```
程序中,我们定义了一个长度为 10 的有序数组 arr,以及要查找的目标元素 target。然后,调用 binarySearch() 函数进行二分查找。函数中,使用 left 和 right 变量分别记录左侧和右侧边界,然后不断缩小边界范围,直到找到目标元素或者边界重合。最后,根据函数返回值输出查找结果。
注意:这只是一个简单的实现,实际应用中可能需要考虑多种情况和优化。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.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)