#include <iostream>
using namespace std;
int binaryFind(int* arr, int len, int target)
{
int left = 0;
int right = len; # 不要用sizeof(arr)/sizeof(arr[0])求数组长度,这样相当于求一个指针所占字节数8/4=2,引入参数len
while (left <= right)
{
int mid = (left + right) / 2;
if (target > arr[mid])
{
left = mid + 1; # 为什么要+1,而不left = mid? 因为 mid
已经搜索过,应该从搜索区间中去除。不+有时会出错,比如(1,2) mid==(1+2)/2==1
}
else if (target < arr[mid])
{
right = mid - 1;
}
else
{
return mid;
}
}
}
int main()
{
int n;
cin >> n;
int* arr = new int[10];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int num;
cin >> num;
cout << "num的下标为" << binaryFind(arr, n, num) << endl;
return 0;
}
关于二分查找算法更多细节: 二分查找算法细节详解_二分查找为什么要加一减一_marytime的博客-CSDN博客
标签:二分,arr,int,mid,查找,left From: https://www.cnblogs.com/xuan4ever/p/17301163.html