C语言的二分法查找

时间:2022-10-27 18:29:25
#include <stdio.h>
void main(){
int s[10]={1,3,6,9,11,28,34,45,46,56};
int left=0,right=sizeof(s)/sizeof(s[0]),middle=0,i=0,m;
printf("请输入查找数字:");
scanf("%d",&m);
while(left<=right){
  
middle=(right+left)/2;
i++;
if(m>s[middle]){
 
left=middle+1;
}else if(m<s[middle]){

        right=middle-1;
}else{
 printf("查找了%d次,查到了%d数据,位置是第%d\n",i,m,middle+1);
 return;

}

}

}