#include<iostream>
#define NULLELEM -1
typedef int ElemType;
using namespace std;
ElemType B_search(int *a ,int l, int r, int v)
{ ElemType tmp;
int m = (l+r)/2;
if( v == a[m]) return a[m];
if( l >= r) return NULLELEM;
if( v < a[m] )
{
tmp = B_search(a, l, m, v);
}
else
{
tmp = B_search(a, m+1, r, v);
}
return tmp;
}
int main()
{ int i;
int a[100];
int d = 26; //需要搜索的元素
for(i = 1; i <= 30; i++)
a[i] = i;
cout<<"The search element "<<d<<" is "<<B_search(a,1,30,d)<<endl;
return 0;
}
总结:
注意递归结束条件(两个if语句)。