1.递归实现
- #include <iostream>
- using std::cout;
- using std::cin;
- using std::endl;
- int BSearch(int *a,int key,int low,int high)
- {
- int mid;
- if(low>high)
- return -1;
- mid=(low+high)/2;
- if(key==a[mid])
- return mid;
- if(key<a[mid])
- return BSearch(&a[0],key,low,mid-1);
- if(key>a[mid])
- return BSearch(&a[0],key,mid+1,high);
- }
- void main()
- {
- int key;
- //cout<<"please input the number"<<endl;
- int a[10]={1,2,3,4,5,8,9,10,11,21};
- cout<<"please input the number"<<endl;
- cin>>key;
- cout<<BSearch(&a[0],key,0,9)<<endl;
- }
2.非递归实现
- #include <iostream>
- using std::cout;
- using std::cin;
- using std::endl;
- int BSearch(int *a,int key,int low,int high)
- {
- while(low<=high)
- {
- int mid=(low+high)/2;
- if(key==a[mid])
- return mid;
- if(key>a[mid])
- {
- low=mid+1;
- }
- if(key<a[mid])
- {
- high=mid-1;
- }
- }
- return -1;
- }
- void main()
- {
- int key;
- //cout<<"please input the number"<<endl;
- int a[10]={1,2,3,4,5,8,9,10,11,21};
- cout<<"please input the number"<<endl;
- cin>>key;
- cout<<BSearch(&a[0],key,0,9)<<endl;
- }