用c语言帮我写个二分查找模板
时间: 2023-03-27 15:03:00 浏览: 77
当然可以,以下是一个简单的二分查找模板:
```c
int binarySearch(int arr[], int l, int r, int x) {
while (l <= r) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] < x)
l = mid + 1;
else
r = mid - 1;
}
return -1;
}
```
其中,arr是要查找的数组,l是数组的左边界,r是数组的右边界,x是要查找的元素。如果找到了x,返回它的下标,否则返回-1。
相关问题
用c语言帮我写一个二分查找
好的,我可以帮您写一个二分查找的程序。以下是示例代码:
```c
#include <stdio.h>
int binarySearch(int arr[], int left, int right, int target) {
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};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 5;
int index = binarySearch(arr, 0, n - 1, target);
if (index != -1) {
printf("目标元素 %d 在数组中的下标为 %d\n", target, index);
} else {
printf("目标元素 %d 不在数组中\n", target);
}
return 0;
}
```
这个程序可以在一个有序数组中查找指定元素的下标,如果找不到则返回 -1。您可以根据需要修改数组和目标元素的值。
帮我用C语言写一个二分查找算法
当然可以!以下是一个简单的二分查找算法的 C 代码示例:
```c
int binary_search(int arr[], int n, int target) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
```
该算法的时间复杂度为 O(log n),其中 n 为数组的大小。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)