//功能:查询某关键在此buf序列中是否存在,如果存在返回其下标,否则返回-1
#include<stdio.h>
short find(int key,int* buf,int ilen);int find1(int buf[],int key,int left,int right);
void main()
{
int buf[]={1,2,3,4,5,6,8,9,10,11,12,13};
short value=find(10,buf,sizeof(buf)/sizeof(int));
short value1=find1(buf,100,0,sizeof(buf)/sizeof(int)-1);
printf("%d\n",value1);
}
{
/*
int i=0;
//f(n)=n
//二分查找:循环,递归
for(i=0;i<ilen;i++)
{
if(buf[i]==key)
return i;
}
*/
int left=0,right=ilen-1,mid;
while(left<=right)//有区间的情况下
{
mid=(left+right)/2;//中间值
if(buf[mid]==key)//查找成功
return mid;
else if(buf[mid]>key)//左侧
right=mid-1;
else//右侧
left=mid+1;
}
return -1;
}
//递归实现二分查找
int find1(int buf[],int key,int left,int right)
{
//结束条件--要么成功,失败
// if(left>right)
// return -1;
//when--开始 when--结束 what-每次递归的步骤
int mid=(left+right)/2;
if(buf[mid]==key)
return mid;
else if(buf[mid]>key)//左侧
return find1(buf,key,left,mid-1);
else
return find1(buf,key,mid+1,right);
}