用C语言编程实现有序表的折半查找算法。创建一个递增(递减)的有序表,给定一个值,用折半查找算法在有序表中进行查找,输出查找结果,给定具体数据调试程序。
时间: 2025-02-03 15:14:37 浏览: 39
折半查找(也称为二分查找)是一种高效的搜索算法,适用于已排序的数据结构,如数组。在C语言中,我们可以使用以下步骤实现折半查找:
首先,定义一个递增或递减的有序整型数组`array[]`,并初始化一个`size`变量表示数组长度。
然后,我们创建一个名为`binarySearch`的函数,接受数组、目标值`target`以及数组长度`size`作为参数。
```c
#include <stdio.h>
// 假设数组是递增排列
int binarySearch(int array[], int size, int target) {
int low = 0;
int high = size - 1;
while (low <= high) {
int mid = (low + high) / 2; // 计算中间索引
if (array[mid] == target) { // 如果找到目标值
return mid;
} else if (array[mid] < target) { // 如果中间元素小于目标,缩小左边界
low = mid + 1;
} else { // 如果中间元素大于目标,缩小右边界
high = mid - 1;
}
}
// 没有找到,返回-1
return -1;
}
int main() {
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int size = sizeof(array) / sizeof(array[0]);
int target = 5; // 或者你想查找的任意数字
int result = binarySearch(array, size, target);
if (result != -1) {
printf("Element found at index %d\n", result);
} else {
printf("Element not found in the array.\n");
}
return 0;
}
```
在这个例子中,如果目标值`5`在数组中,函数会返回它的位置;如果没有找到,返回 `-1`。
你可以根据需要修改`main()`函数中的数组内容和`target`值,进行调试。要测试递减数组,只需改变数组中的元素顺序即可。
阅读全文
相关推荐


















