#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\x0d\x0a\x0d\x0a#define N 20\x0d\x0a\x0d\x0aint Binary(int a[], int n, int found)\x0d\x0a{\x0d\x0aint low = 0\x0d\x0aint high = n - 1\x0d\x0aint mid\x0d\x0ado\x0d\x0a{\x0d\x0amid = (low + high) / 2\x0d\x0aif(found == a[mid])\x0d\x0areturn mid\x0d\x0aelse if(found high = mid - 1\x0d\x0aelse\x0d\x0alow = mid + 1\x0d\x0a}while(low return -1\x0d\x0a}\x0d\x0a\x0d\x0avoid main()\x0d\x0a{\x0d\x0aint found,a[N] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}\x0d\x0aprintf("please input a number\n")\x0d\x0ascanf("%d",&found)\x0d\x0aif(Binary(a,N, found))\x0d\x0aprintf("在数悄返组中基灶的位置是 %d\n",Binary(a,N, found))\x0d\x0aelse\x0d\x0aprintf("没有找启锋饥到\n")\x0d\x0a}#include<stdio.h>int main()
{int a[16]={15,14,13,12,11,10,9,8,7,6,5,4,3,1,0}
int l=0,r=15,mid,x
scanf("%d",&x)
do
{mid=(l+r)/2
if(a[mid]==x)break
if(x>a[mid])r=mid-1
else l=mid+1
}while(l<=r)
if(a[mid]==x)
坦烂 printf("a[%d]=%d\n",mid,x)
else
知局 printf("无此数\n")
return 让猛漏0
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)