一、递归写法
#include<stdio.h>
//设数组是由小到大的顺序排序的
int search_loc(int a[],int k,int low,int high){
int mid;
if(k>a[high]||k<a[low]) //判断是否在数组内
return -1;
if(low>high)
return -1;
mid=(low+high)/2;
if(a[mid]==k)
return mid;
if(a[mid]<k){
return search_loc(a,k,mid+1,high);
}
if(a[mid]>k){
return search_loc(a,k,low,mid-1);
}
return -1;
}
void main()
{
int loc;
int k;
int a[7]={1,2,3,4,5,6,7};
int len=7;
int low=0;
int high=len-1;
printf("请输入需要查找的数:\n");
scanf("%d",&k);
loc=search_loc(a,k,0,6);
printf("%d\n",loc);
}
二、非递归写法
//注意考虑到边界情况,找到则返回在数组中的序号(从0开始),否则返回-1
#include<stdio.h>
int bi_search(int a[],int len,int k){
int low=0;
int high=len-1;
int mid=(low+high)/2;
if(a==NULL||len==0||k<a[low]||k>a[high])
return -1;
while(low<=high){ //考虑边界
if(a[mid]==k)
return mid;
if(a[mid]>k){
high=mid-1;
mid=(low+high)/2;
}
if(a[mid]<k){
low=mid+1;
mid=(low+high)/2;
}
}
return -1;
}
void main(){
int loc;
int a[7]={1,2,3,5,6,7,8};
int k;
scanf("%d",&k);
loc=bi_search(a,7,k);
printf("%d\n",loc);
}