二分查找(无重复的元素) 找到返回下标,找不到返回-1
程序员文章站
2024-03-22 23:26:28
...
从大到小排序:
int bsearch(int A[],int l,int r,int x){
while(l<=r){
int mid=l+r >>1;
if(A[mid]==x) return mid;
else if(A[mid]<x) r=mid-1;
else l=mid+1;
}
return -1;
}
从小到大排序(递归版):
int A[N]={1,3,4,6,7,8,10,11,13,15};
int bsearch(int l,int r,int x){
if(l>r) return -1;
int mid=l+r >>1;
if(A[mid]==x) return mid;
else if(A[mid]<x) return bsearch(mid+1,r,x);//l=mid+1;
else return bsearch(l,mid-1,x);//r=mid-1;
}
非递归版:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=10010;
const int N=10;
int bsearch(int A[],int l,int r,int x){
while(l<=r){
// int mid=l/2+r/2; wrong
int mid=l+r >>1;
if(A[mid]==x) return mid;
else if(A[mid]>x) r=mid-1;
else l=mid+1;
}
return -1;
}
int main(){
const int N=10;
int A[N]={1,3,4,6,7,8,10,11,13,15};
cout<<bsearch(A,0,N-1,6)<<endl;
cout<<bsearch(A,0,N-1,14)<<endl;
return 0;
}
上一篇: ‘’HELLOWORD''图形用户界面