问题
I am implementing binary search in C++. Here is my code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int bs(vector<int> a, int val)
{
int l =0, r = a.size()-1;
while(l<=r) // Significance of ==
{
int mid = l + (r-l)/2;
if(a[mid]==val) return mid;
if(a[mid]>val)
{
r = mid-1; continue;
}
else
{
l = mid + 1 ;
}
}
return l; // Deliberately returning this
}
int main()
{
vector<int> a = {1,3};
cout << bs(a,1) <<endl;
return 0;
}
Question 1
In some implementations, I see people use
while(l<r)
while in some they use
while(l<=r)
Is there any conceptual difference between preferring one way ? Any possible sources of error if I don't use == ?
Question 2
In case the element is not found, is l guaranteed to be the position in which the element could be inserted so that the list still remains sorted ? Is this valid while using equal to or not using equal to ?
回答1:
It depends on how you are calculating variable r
.
In your case
r = a.size()-1;
So correct usage is while(l<=r)
If you calculate r as r = a.size();
correct usage is while(l<r)
In case the element is not found, is l guaranteed to be the position in which the element could be inserted so that the list still remains sorted ?
You didn't sort your vector, for proper binary search, vector should be sorted before calling binary search.
std::sort(std::begin(a),std::end(a));
And header provide a std::binary_search
, so instead reinventing the wheel you can use it as follows:
std::binary_search(std::begin(a),std::end(a),val);
Binary search supposed to return value of index in vector, if it find. But there is no guarantee it should provide the next location for insertion.
Is this valid while using equal to or not using equal to ?
I explained it in first part of my answer.
来源:https://stackoverflow.com/questions/31356239/significance-of-equal-to-in-binary-search