写入数;折半查出.c

来自「用C语言编写。数据结构」· C语言 代码 · 共 49 行

C
49
字号
#include <stdio.h>
#define n 5  
main()
{   int i,j,top,bott,number,mid,loca,a[n],flag=1,sign=1;
    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:");
       }
    printf("\n");
    for(i=0;i<n;i++)printf("%4d",a[i]);
    printf("\n");

    flag=1;
    while(flag)
         {
           printf("Input number to look for:");
           scanf("%d",&number);
           loca=0;
           top=0;
           bott=n-1;
           if((number<a[0])||(number>a[n-1]))loca=-1;
           while((sign==1)&&(top<=bott))
               {
                mid=(bott+top)/2;
                 if(number==a[mid])
                    {
                      loca=mid;
                       printf("Find %d,its position is %d\n",number,loca+1);
                       sign=0;
                      }
                   else if(number<a[mid])bott=mid-1;
                   else top=mid+1;
                    }
             
             if(sign==1||loca==-1)printf("%d is not found.\n",number);
             printf("Continue or not(Y/N)?");
 printf("\n");
             scanf("%c",&c);
             if(c=='N'||c=='n')flag=0;   
            }
    getch();    /* 请不要删除此行 */
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?