c语言二分查找 字符,C语言二分查找

通过数组下标对应的值与要查找的数进行比对,中间下标为最前面的0和数组实际长度减一的平均值,如果要查找的值比中间下标对应的值大,

low=(中间下标+1),middle=(low+hight)/2;如果要查找的值比初始下标对应的值小,hight=中间下标-1,middle=(low+hight)/2

运行结果:

e562547d7b1c

#include

void binarySearch(int a[],int x);

int main(){

int arry[10]={1,3,6,7,9,11,14,15,17,24};

int x;

printf("请输入要查找的数:");

scanf("%d",&x);

binarySearch(arry,x);

}

void binarySearch(int a[],int x){

//查找几次,所在位置

int count=0;//记录次数

int low=0,hight=9;

int meddle;

int flag=0;

while(low<=hight){

count++;

meddle=(low+hight)/2;

if(x==a[meddle]){

printf("查找了%d次找到%d",count,x);

printf("\n%d的位置在%d\n",x,meddle);

flag=1;

break;//要加一个break,否则最后low一直小于等于hight 。也可以用return

}

else if(x>a[meddle]){

low=meddle+1;

}

else{

hight=meddle-1;

}

}

if(flag==0){

printf("没有找到");

}

}

本次单词:binary search二分查找,middle中间的,count 次数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值