折半查找

程序如下:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #define N 5
 4 int main()
 5 {
 6     int i,number,sign,top,bott,mid,loca,flag=1,a[N];
 7     char c;
 8     printf("enter data:
");
 9     scanf("%d",&a[0]);
10     i=1;
11     while(i<N){//输入已排好序的数
12         scanf("%d",&a[i]);
13         if(a[i] >= a[i-1])
14             i++;
15         else
16             printf("enter this data again:
"); 
17     }
18     printf("
");
19     for(i=0;i<N;i++)
20         printf("%5d",a[i]);
21     printf("
");
22     while(flag){
23         printf("input number to look for:");
24         scanf("%d",&number);
25         sign=0;//sign为0表示还未找到
26         top=0;
27         bott=N-1;
28         if((number < a[0]) || (number > a[N-1]))
29             loca=-1;//表示找不到
30         while((!sign) && (top<=bott)){
31             mid=(bott+top)/2;
32             if(number==a[mid]){
33                 loca=mid;
34                 printf("has found %d,its position is %d
",number,loca+1);//loca加一是为了符合阅读习惯
35                 sign=1;//表示已找到
36             }
37             else if(number < a[mid])
38                 bott=mid-1;
39             else
40                 top=mid +1;
41         }
42         if(!sign || loca==-1)//循环结束后,判断
43             printf("cannot find %d
",number);
44         printf("contine or not(Y/N)?");
45         scanf(" %c",&c);
46         if(c=='N'||c=='n')
47             flag=0;
48     }
49     system("pause");
50     return 0;
51 }
原文地址:https://www.cnblogs.com/crystalmoore/p/5923763.html