用c++写一个二分法查找
时间: 2024-02-18 13:28:39 浏览: 150
好的,以下是用 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;
}
int main() {
int arr[] = {1, 3, 5, 7, 9, 11};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 7;
int result = binarySearch(arr, 0, n-1, target);
if (result == -1) {
printf("Element not found in the array.\n");
} else {
printf("Element found at index %d.\n", result);
}
return 0;
}
```
在这个程序中,我们先定义了一个 `binarySearch` 函数,它接收一个整数数组 `arr`,一个表示数组左端点的整数 `low`,一个表示数组右端点的整数 `high`,以及要查找的目标值 `target`。该函数返回目标值的下标,如果目标值不存在,则返回 -1。
在函数中,我们使用了一个 while 循环来进行二分查找。每次循环中,我们计算出中间点的下标 `mid`,然后比较中间点的值与目标值的大小。如果中间点的值等于目标值,则返回中间点的下标。如果中间点的值小于目标值,则说明目标值在右半部分数组中,我们将左端点 `low` 更新为 `mid + 1`。如果中间点的值大于目标值,则说明目标值在左半部分数组中,我们将右端点 `high` 更新为 `mid - 1`。
在 main 函数中,我们定义了一个整数数组 `arr`,以及要查找的目标值 `target`。然后,我们调用 `binarySearch` 函数来查找目标值在数组中的位置。如果返回值为 -1,则说明目标值不存在于数组中。否则,返回值为目标值在数组中的下标。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.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)
![](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)