Recursive algorithm to implement binary search c++

Recursive algorithms can be used to implement binary search. Binary search is an efficient search algorithm for sorted arrays. The following is an example code that uses a recursive algorithm to implement a binary search:

#include <iostream>
using namespace std;

// 递归二分查找函数
int binarySearch(int arr[], int low, int high, int target) {
    
    
    if (low > high) {
    
    
        return -1; // 查找失败,返回-1
    }

    int mid = low + (high - low) / 2; // 计算中间元素的下标

    if (arr[mid] == target) {
    
    
        return mid;  // 找到目标元素,返回下标
    } else if (arr[mid] > target) {
    
    
        return binarySearch(arr, low, mid - 1, target); // 目标元素在左半部分,继续递归查找
    } else {
    
    
        return binarySearch(arr, mid + 1, high, target); // 目标元素在右半部分,继续递归查找
    }
}

int main() {
    
    
    int arr[] = {
    
    2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 12;

    int result = binarySearch(arr, 0, n - 1, target);

    if (result == -1) {
    
    
        cout << "目标元素未找到" << endl;
    } else {
    
    
        cout << "目标元素的下标为 " << result << endl;
    }

    return 0;
}

In the above example code, binarySearchthe function receives as parameters a sorted array of integers arr, the lowest index low, the highest index of the array high, and the target element target. First, determine lowwhether it is greater than the value high. If so, the search fails and -1 is returned. Then, calculate the subscript of the middle element mid. If the middle element is equal to the target element, return the index of the middle element. If the middle element is larger than the target element, the target element is in the left half of the array, and the function continues to be called recursively binarySearchto find the target element in the left half. If the middle element is smaller than the target element, the target element is in the right half of the array, and the function continues to be called recursively binarySearchto find the target element in the right half.

In mainthe function, create a sorted array of integers arrand specify the target element to find target. Then call binarySearchthe function to perform a binary search and determine whether the target element is found based on the return value.

Running the above code, the output is:

目标元素的下标为 5

This means that 12the index of the target element in the array is 5.

Hope the above code can solve your problem. If you have any further questions, please feel free to ask.

Guess you like

Origin blog.csdn.net/wzxue1984/article/details/132948428