二分查找算法2

/* 递归结构的二分查找 */

#include <iostream>

using namespace std;

int BSearch(int a[],int x,int low,int high);

void main()

{

while (1)

{

int a[]={1,3,4,5,17,18,31,33};

int x;

cin >> x;

int bn;

bn=BSearch(a,x,0,7);

if (bn==-1)cout<<"x不在数组a中!"<<endl;

else

cout<<"x在数组a的下标是:"<<bn<<endl;

}

}

int BSearch(int a[],int x,int low,int high)

{

int mid;

if(low>high)return -1; //查找不成功

mid=(low+high)/2;

if(x==a[mid])return mid; //查找成功

else if(x<a[mid])

BSearch(a,x,low,mid-1); //在下半区查找 //此处不用return!!

else

BSearch(a,x,mid+1,high); //在上半区查找

}

你可能感兴趣的:(二分查找)