递归实现二分法查找的思路如下: 首先定义一个函数,接收一个有序数组、待查找的元素、数组的起始位置和结束位置作为参数。 在函数中,首
递归实现二分法查找的思路如下:
下面是一个用递归实现二分法查找的示例代码:
#include <stdio.h>
int binarySearch(int arr[], int target, int start, int end) {
if (start > end) {
return -1;
}
int mid = (start + end) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] > target) {
return binarySearch(arr, target, start, mid - 1);
} else {
return binarySearch(arr, target, mid + 1, end);
}
}
int main() {
int arr[] = {1, 3, 5, 7, 9};
int target = 5;
int result = binarySearch(arr, target, 0, sizeof(arr) / sizeof(arr[0]) - 1);
if (result == -1) {
printf("Element not found\n");
} else {
printf("Element found at index %d\n", result);
}
return 0;
}
以上代码中,我们定义了binarySearch
函数来实现二分法查找,然后在main
函数中调用该函数进行查找。输出结果为Element found at index 2
,表示在给定数组中找到了待查找的元素,并返回其索引位置为2。
--结束END--
本文标题: c语言中怎么用递归实现二分法查找
本文链接: https://www.lsjlt.com/news/570199.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0