运行代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main(vodi)
{
//二分查找:
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
int left = 0;
int right = sizeof(arr) / sizeof(arr[0]);
int x = 0;
scanf("%d", &x);
while (left <= right)
{
int mid = (left + right) / 2;
if (arr[mid] > x)
right = mid - 1;
else if (arr[mid] < x)
left = mid + 1;
else
{
printf("Find!,the subscript is %d", mid);
break;
}
}
if (left > right)
printf("NO Find!\n");
return 0;
}
运行结果截图
注意:
**当(left+right)/2大于Int的取值范围时,则会导致数据溢出,故这种写法并不是完美的,
可以将int mid = (left + right) / 2;改为:int mid=left+(right-left)/2;这样就可以完美的解决bug了!!!**
画一个这个图,希望帮助大家理解!