#include <stdio.h>
int main()
{
int i, j, n, k=0, isFound=0
int num[15] = {88,86,75,74,61,56,52,43,39,34,31,22,18,16,8} //测试数组
printf("请输出一个整数:\n")
scanf("%d", &n)
i = (int)15/2 //对折位移量
j = (int)15/2 //取数“指针”
while(k<2)
{
i = (int)i/2
if(i == 0) k++//i==0 即折半到无可再折时,仍有最后一次比较,故以k做计数
//若未相等,计算下一循环指针的位置
if(n<num[j])
j = j + (i + 1)
else if(n>num[j])
j = j - (i + 1)
else
{
isFound = 1
break //若找到相等数,标记已找到并退出循环
}
}
//输出结果
if(isFound)
printf("该数是数组中第%d个元素的值\n", j)
else
printf("查无此数!\n")
return 0
}
#include<stdio.h>
int find(int a[],int x,int n,int m)
{int i
if(n>m)return -1
i=(n+m)/2
if(a[i]==x)return i
if(a[i]>x)return find(a,x,n,i-1)
return find(a,x,i+1,m)
}
int main()
{
int a[20]={2,3,6,7,12,18,19,21,25,28,30,33,37,39,42,45,47,49,50,51}
int x,i
printf("已有的数是:\n")
for(i=0i<20i++)
printf("%d ",a[i])
printf("\n请输入要查找的数:")
scanf("%d",&x)
if((i=find(a,x,0,19))>=0)
printf("%d是第%d个数\n",x,i+1)
else printf("未找到%d\n",x)
return 0
}
#include<stdio.h>
int main()
{
char a[12]="abcdefklmnp",ch
int i,top,bot,mid
printf("Input a character\n")
scanf("%c",&ch)
printf("ch=%c\n",ch)
top=11
bot=0
mid=(top+bot)/2
while(bot<=top&&a[mid]!=ch)
{if(a[mid]>ch)top=mid-1
else if(a[mid]==ch)break
else bot=mid+1
mid=(top+bot)/2
}
if(a[mid]==ch)printf("第%d个字符就是%c\n",mid+1,ch)
if(bot>top)printf("该字符不存在a中\n")
return 0
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)