从键盘输入一个整数,用折半查找法找出该数在10个有序整型数组a中的位置。若该数不在a中,则打印出相应信息。试编程。
#include <stdio.h>
// 折半查找函数
int binary_search(int arr[], int size, int target) {
int low = 0, high = size - 1;
while (low <= high) {
int mid = (low + high) / 2;
int mid_value = arr[mid];
if (mid_value == target) {
return mid; // 找到目标数,返回索引
} else if (mid_value < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1; // 目标数不在数组中
}
int main() {
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int size = sizeof(a) / sizeof(a[0]);
// 从键盘输入一个整数
int target;
printf("请输入要查找的整数:");
scanf("%d", &target);
// 调用折半查找函数
int result = binary_search(a, size, target);
// 输出结果
if (result != -1) {
printf("数字 %d 在数组中的位置是 %d\n", target, result);
} else {
printf("数字 %d 不在数组中\n", target);
}
return 0;
}