用C++写一个二分查找的代码
时间: 2023-12-27 09:58:34 浏览: 23
#include<stdio.h>
int binarySearch(int arr[], int low, int high, int x)
{
if (high >= low)
{
int mid = (low + high)/2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, low, mid-1, x);
return binarySearch(arr, mid+1, high, x);
}
return -1;
}
int main()
{
int arr[] = {2, 3, 4, 10, 40};
int x = 10;
int n = sizeof(arr)/ sizeof(arr[0]);
int result = binarySearch(arr, 0, n-1, x);
(result == -1)? printf("元素未找到")
: printf("元素在索引 %d 处", result);
return 0;
}
相关问题
用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(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
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;
}
帮我用c++写一个二分查找的代码
下面是使用C语言编写的二分查找代码:
```c
#include <stdio.h>
int binarySearch(int arr[], int low, int high, int target)
{
int mid;
while (low <= high) {
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, 13};
int target = 9;
int n = sizeof(arr) / sizeof(arr[0]);
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的函数,该函数接受一个整数数组、一个下限、一个上限和一个目标整数作为参数,并返回目标整数在数组中的索引。在函数中,我们使用while循环来查找目标整数。我们首先计算中间元素的索引,然后比较该元素与目标整数的大小。如果它们相等,则返回该元素的索引。如果中间元素小于目标整数,则我们在右半部分数组中继续查找。否则,我们在左半部分数组中继续查找。如果我们没有找到目标整数,则在函数退出前返回-1。在main函数中,我们定义了一个整数数组,并使用binarySearch函数来查找目标整数。如果找到了目标整数,则打印其索引。否则,我们打印一个错误信息。