设计思路
1.头尾下标怎么定义
2.mid的表示合理(考虑溢出)
3.先写出一次判断经过的步骤
4.嵌套循环即可
时间复杂度:log2N
代码:
//二分查找
#include<stdio.h>
int main()
{
int arr[10] = {1,2,3,4,5,6,7,8,9,10 };
int left = 0;
int right = sizeof(arr) /sizeof(arr[0]) - 1;//数组元素个数等于数组所占内存/单个元素所占内存
//尾元素数组下标=元素个数-1
int mid = 0;
int target = 0;
scanf("%d", &target);
mid = left + (right - left) / 2; //mid=(left+right)可能会整数溢出
while (left <= right) {
if (arr[mid] > target)
{
left = mid + 1;
}
else if (arr[mid] < target)
{
right = mid - 1;
}
else
{
printf("找到了,他的下标是:%d", mid);
break;
}
}
if (left > right)
printf("没找到");
return 0;
}