A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© sunshine429 中级黑马   /  2016-1-2 22:34  /  695 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. #define M 10
  2. #include<stdio.h>

  3. void main()
  4. {
  5.       static int a[M]={-12,0,6,16,23,56,80,100,110,115};
  6.       int n, low, mid, high, found;
  7.       low=0;   
  8.       high=M-1;   
  9.       found=0;
  10.       printf("Input a number to be searched:");
  11.       scanf("%d", &n);
  12.       
  13.       while(low <= high)
  14.       {
  15.             mid = (low + high) / 2;            

  16.             if (n == a[mid])
  17.             {
  18.                   found = 1;     
  19.                   break;
  20.             }/*找到,结束循环*/

  21.             else if (n > a[mid])
  22.             {
  23.                   low=mid+1;
  24.             }
  25.             else
  26.             {
  27.                   high=mid-1;
  28.             }
  29.       }
  30.       
  31.       if (found==1)
  32.       {
  33.             printf("The index of %d is %d\n", n, mid);
  34.       }
  35.       else
  36.       {
  37.             printf("There is not  %d\n", n);
  38.       }
  39. }
复制代码

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马