核心代码(循环);
int f= -1;
while(left<=right){
mid=(left+right)/2;
if(a[mid]==key){
f=mid;
break;
}
if(key<a[mid]) r=mid-1;
if(key>a[mid]) l=mid+1;
}
if(f==-1) cout<<"没找到";
else cout <<f<<endl;
核心代码(递归):
int binsearch(int left,int right){
if(left<=right){
int mid=(left+right)/2;
if(a[mid]==key) return mid;
if(key<a[mid]) return binsearch(left,mid-1);
if(key>a[mid]) return binsearch(mid+1,right);
}
else return 0;
}
例题
输入n和n个整数,使用冒泡排序将其从小到大排序,输出排序前和排序后的结果
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
int key;
cin>>key;
int l=0;int r=n-1;
int mid;
int f= -1;
while(l<=r){
mid=(l+r)/2;
if(a[mid]==key){
f=mid;
break;
}
if(key<a[mid]) r=mid-1;
if(key>a[mid]) l=mid+1;
}
if(f==-1) cout<<"没找到";
else cout <<f<<endl;
}