#include<stdio.h>
void main()
{
int arr[100] = { 1};
for (int j = 0; j < 100; j++)
{
arr[j] = j+1;
}
int sz = sizeof(arr) / sizeof(arr[0]);
int left = 0;
int i = 0;
int right = sz - 1;
int ret = 101;
while (left <= right)
{
++i;
int mid = (left + right) / 2;
if (arr[mid] > ret)
{
right = mid - 1;
}
else if (arr[mid] < ret)
{
left = mid + 1;
}
else
{
printf("%d\n", mid);
if (arr[mid] == ret)
{
break;
}
}
}
printf("%d\n", i);
}
二分查找在进行时,查找的是对应元素的索引:
把arr赋值为1-100;往右边查找101,返回的 i (查找次数) 是 7次,往左边查找0的话,返回的次数就是6次。