数据结构与算法(C语言版)__递归的折半查找

下面对比递归和迭代算法实现二分查找:
折半查找每次都要折半,所以可以使用递归的方法。

#include<iostream>

using namespace std;

int BinarySearch_I(int *a, const int x, const int n);
int BinarySearch_R(int *a, const int x, const int left, const int right);

int main(){
    int m[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int 结果;
    int num = 4;
    结果 = BinarySearch_R(m, num, 0, 8);
    if (结果 < 0)
        cout << "递归算法没找到" << endl;
    else
        cout << "递归算法:在m[" << 结果 << "]找到" << num << endl;
    结果 = BinarySearch_I(m, num, 8);
    if (结果 < 0)
        cout << "迭代算法没找到" << endl;
    else
        cout << "迭代算法:在m[" << 结果 << "]找到" << num << endl;
    system("pause");
    return 0;
}
//迭代法
int BinarySearch_I(int *a, const int x, const int n){
    int left = 0, right = 8;
    while (left <= right){
        int middle = (left + right) / 2;
        if (x < a[middle])right = middle - 1;
        else if (x>a[middle])left = middle + 1;
        else return middle;
    }
    return -1;
}
//递归法
int BinarySearch_R(int *a, const int x, const int left, const int right){
    if (left <= right){
        int middle = (left + right) / 2;
        if (x < a[middle])return BinarySearch_R(a, x, left, middle - 1);
        else if (x > a[middle])return BinarySearch_R(a, x, middle + 1, right);
        else return middle;
    }
    return -1;
}

总结:很多复杂的算法都是使用递归来实现,所以递归需要好好掌握。

    原文作者:查找算法
    原文地址: https://blog.csdn.net/chenlou123/article/details/53748168
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞