用c语言二分查找分治算法查找多个数的代码
时间: 2023-04-06 07:02:42 浏览: 112
以下是用C语言实现二分查找分治算法查找多个数的代码:
```c
#include <stdio.h>
int binarySearch(int arr[], int low, int high, int target) {
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
void binarySearchMultiple(int arr[], int n, int targets[], int m) {
for (int i = 0; i < m; i++) {
int index = binarySearch(arr, 0, n - 1, targets[i]);
if (index == -1) {
printf("%d not found\n", targets[i]);
} else {
printf("%d found at index %d\n", targets[i], index);
}
}
}
int main() {
int arr[] = {1, 3, 5, 7, 9};
int targets[] = {2, 4, 6, 8};
int n = sizeof(arr) / sizeof(arr[0]);
int m = sizeof(targets) / sizeof(targets[0]);
binarySearchMultiple(arr, n, targets, m);
return 0;
}
```
这个程序可以在一个有序数组中查找多个数,并输出它们在数组中的位置。如果某个数不在数组中,则输出“not found”。
阅读全文