二分查找(递归)
#include<stdio.h>
int BSearch(int a[],int low,int high,int x){
if(low > high) return -1;
int mid = (low + high )/ 2;
if(a[mid] == x) return mid;
else if(a[mid]<x) return BSearch(a,mid+1,high,x);
else return BSearch(a,low,mid-1,x);
}
int main(){
int a[] = {2, 3, 4, 10,40,55,61,72,73,88,90,95,100};
int x;
int n = sizeof(a) / sizeof(a[0]);
scanf("%d",&x);
int res = BSearch(a,0,n-1,x);
if(res == -1){
printf("不存在此元素");
}
else
printf("%d %d",res,a[res]);
}
非递归版
#include<stdio.h>
int BSearch(int a[],int n,int x){
int low = 0;
int high = n;
while(low<=high){
int mid = (low+high)/2;
if(a[mid]==x) return mid;
else if(a[mid]<x) low = mid+1;
else high = mid -1;
}
return -1;
}
int main(){
int a[] = {2,3,4,10,40,55,61,72,73,88,90,95,100};
int x;
int n = sizeof(a) / sizeof(a[0]);
scanf("%d",&x);
int res = BSearch(a,n-1,x);
if(res == -1){
printf("不存在此元素");
}
else
printf("%d %d ",res,a[res]);
}