二分查找 输出元素下标

#include <stdio.h>
#include <stdlib.h>
#define n 6
/* 折半查找法找出该数是数组中第几个元素的值,如果不在数组中,则输出”无此数”*/
int main(int argc, char *argv[]) {
int a[n]={1,3,5,7,9,10};// 012345 5/2=2 4<5 and mid-1 //(high= 1 low=0 and mid =0)
    // int i; 
int high=n-1,low=0;
    int mid=(high+low)/2;
    int num;//the num is the input number 
scanf("%d",&num); 
while(low<=high) //0<5 mid=2,3<a[2]=5, high=1, ||2.and mid=0 low=0,high=1  3>1 3.low=mid+1=1 high=1 and the mid =1 finally 3==3 printf("the mark is 1")
{
if(num>a[mid])
{
low=mid+1;
}
if(num<a[mid])
{
high=mid-1;
}
if(num==a[mid])
{
printf(" the mark is %d\n",mid);
            break;// fine it ,so stop down //
}
mid=(low+high)/2;
}
if(low>high)
printf("not exist!");
return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值