首页 > 代码库 > 2017/1/8 C语言程序练习d

2017/1/8 C语言程序练习d

有10个数按由小到大顺序存放在一个数组中,输入一个数,要求用折半查找法找出该数是数组中第几个元素的值。如果该数不在数组中,则打印出“无此数”。

输入:-12 -8 12 24 45 46 56 58 68 78

输入要查找的数据:58

输出:58的下标为7

输入要查找的数据:21

输出:”无此数”

#include"stdio.h"

 

void chazhao (int a[])

{

       int i,s,mid,high,low,flag=1,n=0;

 

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

       scanf("%d",&s);

 

       for(i=0;i<10;i++)

              if(s==a[i])

                     n=1;

       if(n==0)

       {

              printf("无此数\n");

              flag=0;

       }

 

       while(flag)

       {

              high=10;

              low=0;

              while(low<=high)

              {

                     mid=(high+low)/2;

                     if(s==a[mid])

                     {

                            printf("%d的下标是%d\n",s,mid);

                            flag=0;

                            break;

                     }

                     if(s<a[mid])

                     {

                            high=mid;

                     }

                     if(s>a[mid])

                     {

                            low=mid;

                     }

              }

 

       }

}

 

void main()

{

       int a[10];

       int i,j;

 

       for(i=0;i<10;i++)

              scanf("%d",&a[i]);

 

       chazhao(a);

}

2017/1/8 C语言程序练习d