用C语言编写可运行的代码实现以下功能一、用C语言编程实现有序表的折半查找算法1、 创建一个递增的有序表;2、 给定一个值用折半查找算法在有序表中进行查找;3、 输出查找结果;4、 给定具体数据调试程序
#include <stdio.h>
// 折半查找函数 int binarySearch(int arr[], int n, int target) { int left = 0; int right = n - 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;
}
int main() { // 创建递增有序表 int arr[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}; int n = sizeof(arr) / sizeof(arr[0]);
// 给定一个值
int target = 11;
// 使用折半查找算法在有序表中查找
int result = binarySearch(arr, n, target);
// 输出查找结果
if (result == -1) {
printf("目标值 %d 不在有序表中\n", target);
}
else {
printf("目标值 %d 在有序表的第 %d 个位置\n", target, result + 1);
}
return 0;
原文地址: https://www.cveoy.top/t/topic/hBBY 著作权归作者所有。请勿转载和采集!