使用c++写一个二分查找
时间: 2024-05-06 20:21:30 浏览: 8
好的,以下是使用 C 语言编写的二分查找算法:
```c
#include <stdio.h>
int binarySearch(int arr[], int l, int r, int x) {
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
return binarySearch(arr, mid + 1, r, x);
}
return -1;
}
int main() {
int arr[] = {2, 4, 6, 8, 10};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 8;
int result = binarySearch(arr, 0, n - 1, x);
(result == -1) ? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}
```
以上代码实现了二分查找算法,其中将要查找的数存储在变量 `x` 中,数组存储在 `arr` 中,`n` 变量表示数组中的元素个数。程序运行后,将输出查找结果,如果查找的数不存在于数组中,则输出 "Element is not present in array",否则输出 "Element is present at index n",其中 n 是查找到的数字在数组中的下标。