谭浩强第六章9题 折半查找法找出数组元素

简易版:


#include <stdio.h>
#define N 10
int main()
{
    int a[N]={98,87,76,65,54,43,32,21,10,1};
    int mid,loca,top,bott,num;
    top=0;
    bott=N-1;
    mid=(top+bott)/2;
    printf("please input a number you look:");
    scanf("%d",&num);
    for (int i = top; i <= bott; ++i) {
        if(a[mid]>num){
            top=mid;
            mid=(top+bott)/2;
        }
        if (a[mid]<num){
            bott=mid;
            mid=(top+bott)/2;
        }
        if (a[mid]==num){
            printf("the number is %d shang\n",mid);
            break;
        }
    }
    return 0;
}


精进版:

#include <stdio.h>
#define  N 15
int main()
{
    int i,number,top,bott,mid,loca,a[N],flag=1,sign;
    char c;
    printf("enter data:\n");
    scanf("%d",&a[0]);
    i=1;
    while(i<N)
    {
        scanf("%d",&a[i]);
        if (a[i]>=a[i-1])
            i++;
        else
            printf("enter this data again:\n");
    }
    printf("\n");
    for (i=0;i<N;i++)
        printf("%5d",a[i]);
    printf("\n");
    while(flag)
    {
        printf("input number to look for:");
        scanf("%d",&number);
        sign=0;
        top=0;                //top是查找区间的起始位置
        bott=N-1;             //bott是查找区间的最末位置
        if ((number<a[0])||(number>a[N-1]))  //要查的数不在查找区间内
            loca=-1;        // 表示找不到
        while ((!sign) && (top<=bott))
        {
            mid=(bott+top)/2;
            if (number==a[mid])
            {
                loca=mid;
                printf("Has found %d, its position is %d\n",number,loca+1);
                sign=1;
            }
            else if (number<a[mid])
                bott=mid-1;
            else
                top=mid+1;
        }

        if(!sign||loca==-1)
            printf("cannot find %d.\n",number);;
        printf("continu or not(Y/N)?");
        scanf(" %c",&c);
        if (c=='N'||c=='n')
            flag=0;
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值