二分查找法 c语言程序设计?

2024-12-03 17:55:57
推荐回答(3个)
回答(1):

我给你一个例子:
#include
#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 {
mid=(left+right)/2;
if(k==table[mid])
find=1;
else if(k 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);
}

回答(2):

#include

int binfind(int val[] , int num , int value)
{
int start = 0;
int end = num - 1;
int mid = (start + end)/2;
while(val[mid] != value && start < end)
{
if (val[mid] > value)
{
end = mid - 1;
}
else if (val[mid] < value)
{
start = mid + 1;
}
mid = ( start + end )/2;
}
if (val[mid] == value)
return mid;
else
return -1;
}

int main()
{
int nums[] = {1 , 3 , 4 ,7 ,8 , 12 ,45 ,67 ,97 ,123 ,456 ,675 ,1111 , 4534 , 4563};
int result = binfind(nums , sizeof(nums) / sizeof(nums[0]) , 45);
if (result < 0)
{
printf("查无此数");
}

}

回答(3):

比如要在0到100中找42
那么先2分
50不是
50>40
再2分
25
依次
直到找到