请使用C语言写二分查找哦
时间: 2023-07-19 20:07:51 浏览: 40
好的,以下是使用C语言写的二分查找算法:
```c
#include <stdio.h>
int binary_search(int arr[], int n, int target) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 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};
int n = sizeof(arr) / sizeof(int);
int target = 5;
int index = binary_search(arr, n, target);
if (index == -1) {
printf("未找到目标元素\n");
} else {
printf("目标元素在数组中的下标为: %d\n", index);
}
return 0;
}
```
运行结果:
```
目标元素在数组中的下标为: 2
```