#include <stdio.h>
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("查無此數");
#include <stdio.h>
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("查無此數");
}
}