c语言实现输入n(n<100)的值,以及n个从小到大排序的整数序列,再输入一个待查找的整数m,使用二分法进行查找该数的序号。
时间: 2024-05-03 08:19:52 浏览: 141
这个问题属于技术问题,可以回答。以下是代码示例:
```c
#include <stdio.h>
int search(int arr[], int n, int target) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1; // target not found
}
int main() {
int n;
printf("Enter the number of integers: ");
scanf("%d", &n);
if (n > 100) {
printf("n is too large.\n");
return 1;
}
int arr[n];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int m;
printf("Enter the number to search: ");
scanf("%d", &m);
int result = search(arr, n, m);
if (result == -1) {
printf("%d not found.\n", m);
} else {
printf("%d found at index %d.\n", m, result);
}
return 0;
}
```
阅读全文