递归实现二分法查找的思路如下:
下面是一个用递归实现二分法查找的示例代码:
#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。