2013-06-29
展开全部
我用一个子函数实现的,主函数你自己写,对你又好处,需要传入一个数组和数组长度n以及要查找的数,如果查找成功,返回x在数组中的位置,否则返回-1
int search(int *a,int x)
{ int low=0,high=n-1,mid,flag=-1;
while(low<=high)
{ mid=(low+high)/2;
if(a[mid]==x) return mid;
else if(a[mid]>low) low=mid+1;
else high=mid-1;
}
return flag;
}
int search(int *a,int x)
{ int low=0,high=n-1,mid,flag=-1;
while(low<=high)
{ mid=(low+high)/2;
if(a[mid]==x) return mid;
else if(a[mid]>low) low=mid+1;
else high=mid-1;
}
return flag;
}
2013-06-29
展开全部
#include<stdio.h>
#define N 10
main()
{
int k,i;
int table[N]={0,2,4,6,8,10,12,14,16,18};
int mid,left=0,right=N-1;
int find=0;
printf("input your number:");
scanf("%d",&k);
while(!find&&left<right)
{
mid=(left+right)/2;
if(k==table[mid])
find=1;
else if(k<table[mid])
right=mid-1;
else left=mid+1;
}
if(find==1)
printf("%d in table[%d]\n",k,mid);
else
printf("can't find the number%d.\n",k);
}
#define N 10
main()
{
int k,i;
int table[N]={0,2,4,6,8,10,12,14,16,18};
int mid,left=0,right=N-1;
int find=0;
printf("input your number:");
scanf("%d",&k);
while(!find&&left<right)
{
mid=(left+right)/2;
if(k==table[mid])
find=1;
else if(k<table[mid])
right=mid-1;
else left=mid+1;
}
if(find==1)
printf("%d in table[%d]\n",k,mid);
else
printf("can't find the number%d.\n",k);
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询