递归折半查找

递归封神!

#include

using namespace std;

int BinarySearch_I(int *a,const int x,const int n);//迭代查找,x为查找的关键字,n为数组长度

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

int main(){

    int a[]={1,2,3,8,7,6,2};

    cout<<"迭代查找";

    cout<

    cout<<"递归查找";

cout<

return 0;

}

int BinarySearch_I(int *a,const int x,const int n){  //迭代查找

int left=0;

int right=n-1;

int middle=(left+right)/2;

while(left<=right){

if(x>a[middle]){

left=middle;

middle=(left+right)/2;

}

else if(x

    right=middle;

middle=(left+right)/2;


}

else   

return middle; 

  }

return -1;

}

int BinarySearch_R(int *a,const int x,int left,int right){ //递归

if(left<=right){

int middle=(left+right)/2;

if(x

return BinarySearch_R(a,x,left, middle-1);

}

else if(x>a[middle]){

return BinarySearch_R(a,x,middle+1,right);

}

else return middle;

    }

    else return -1;

}

最大的感慨,代码光看是不行的。要实践。知行合一,方为上策。

你可能感兴趣的:(递归折半查找)