递归折半查找

2019-06-28  本文已影响0人  朱宏飞

递归封神!

#include <iostream>

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<<BinarySearch_I(a,3,7);

    cout<<"递归查找";

cout<<BinarySearch_R(a,3,0,6);

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<a[middle]){

    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<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;

    }

    else return -1;

}

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

上一篇下一篇

猜你喜欢

热点阅读