【C语言】折半查找15个数中的某一数【原创技术】
(2012-04-08 11:59:36)
标签:
折半查找数组c语言此数个数it |
分类: C语言 |
题目:
有15个数存放在一个数组中,输入一个数要求用折半查找法找出该数是数组中的第几个元素的值,如果该数不在数组中,则输出无此数,要找的数用scanf函数输入。
源代码:
#include"stdio.h"
#include"math.h"
#defineN 15
voidmain()
{
inttop,bott,a[N]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int number=0;
int mid;
bool flag;
int loca=0;
int sign=1;
char c;
scanf("%d",&number);
while(flag)
{
loca=0;
top=0;
bott=N-1;
if(number<a[0]||number>a[N-1])
loca=-1;
while(sign==1 && top<=bott && loca>=0)
{
mid=(bott+top)/2;
if(number==a[mid])
{
loca=mid;
printf("找到了,数%d在数组的第%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("\n查无此数\n");
printf("\n是否继续查找?(Y/N)");
scanf("%c",&c);
getchar(number);
printf("\n");
if(c=='N'||c=='n') flag=0;
}
}
更多详细内容: 去学习

加载中…