算法:递归与迭代

//利用递归进行折半查找
//迭代的折半查找

#include 
using namespace std;
int BinarySearch_I(int *a, const int x, const int n); //迭代查找  指针a代表数组
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,10};
    int i;
    int num = 7;
    if((i = BinarySearch_R(m,num,0,9)<0))
        cout <<"没找到"< 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;
}

你可能感兴趣的:(数据结构)