从键盘输入10个已排序的整数到数组a中(从小到大),然后输入另外一个待查找的整数b,采用二分查找(折半查找)算法查找整数b在数组a中的位置,如果找到,则显示该元素的下标,如果没有找到,则显示-1。
时间: 2024-02-20 22:56:38 浏览: 27
好的,这是一个简单的二分查找算法的实现。以下是代码:
```c
#include <stdio.h>
int binary_search(int arr[], int n, int target) {
int left = 0, right = n - 1, mid;
while (left <= right) {
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[10], target, idx;
printf("Please input 10 sorted integers: ");
for (int i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
printf("Please input the target integer: ");
scanf("%d", &target);
idx = binary_search(arr, 10, target);
if (idx == -1) {
printf("The target integer is not found.\n");
} else {
printf("The target integer is at index %d.\n", idx);
}
return 0;
}
```
运行结果:
```
Please input 10 sorted integers: 1 2 3 4 5 6 7 8 9 10
Please input the target integer: 7
The target integer is at index 6.
```
阅读全文