首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

帮小弟我看看2分查找法

2012-03-15 
帮我看看2分查找法/*在排好序的数组中,输入一个数查找其位置,没有就输出无此数,有就输出位置*/#include s

帮我看看2分查找法
/*在排好序的数组中,输入一个数查找其位置,没有就输出无此数,有就输出位置*/

#include <stdio.h>
#define   N   15
void   main()
{
int   i,number,top,bott,mid,loca,a[N],sign,flag=1;
char   c;
printf( "enter   data(total   15):\n ");
scanf( "%d ",&a[0]);
i=1;
while(i <N)//until   N-1输入数据
{scanf( "%d ",&a[i]);
if(a[i]> =a[i-1])     //如果输入的是非数字,那么将引起错误
    i++;
else
    printf( "enter   this   data   again:\n ");
}

printf( "\n ");//put   out   all   data
for(i=0;i <N;i++)
      printf( "%d   ",a[i]);
printf( "\n ");

while(flag)
{
    printf( "input   a   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=(top+bott)/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( "can   not   find   %d\n ",number);
    printf( "countine   or   not(Y/N)? ");
    scanf( "%c ",&c);
    if((c== 'n ')||(c== 'N '))
        flag=0;
}
}

enter   data(total   15):
1
2
3
4
5
6
7
8
9
10
20
30
40
50
60

1   2   3   4   5   6   7   8   9   10   20   30   40   50   60
input   a   number   to   look   for:6
Has   found   6,its   position   is   6
countine   or   not(Y/N)?input   a   number   to   look   for:
怎么多一句input   a   number   to   look   for:??

[解决办法]
没有清内存引起的。在语句printf( "countine or not(Y/N)? ");前加上fflush(stdin)就可解决。

热点排行