#include<iostream>
#define NULLELEM -1
typedef int ElemType;
using namespace std;
ElemType B_search(int *a ,int l, int r, int v)
{
while(l <= r)
{
int m = (r+l)/2;
if(a[m] == v) { return a[m]; }
if( v < a[m] )
r = m - 1 ;
else if( v > a[m])
l = m + 1;
}
return NULLELEM;
}
int main()
{ int i;
int a[100];
int d = 129; //需要搜索的元素
for (i = 1; i <= 30; i++)
a[i] = i;
cout<<"The search element "<<d<<" is "<<B_search(a,1,30,d)<<endl;
return 0;
}
总结:二分搜索的迭代过程要注意。下标等细节要注意。考虑清楚了,可以对代码进行简单优化。