I need a binary search function.
I couldn\'t find any function in the standard library that will return the index of the found item, and if it wasn\'t found,
I'm quite certain the standard library doesn't include anything to do precisely what you're asking for.
To get what you want, you'll probably want to start from std::lower_bound
or std::upper_bound
, and convert the iterator it returns into an index, then complement the index of the value wasn't found.
int bin_search (ForwardIterator first, ForwardIterator last, const T& val)
{
ForwardIterator low;
low = std::lower_bound(first,last,val);
if(low!=last && !(val<*low)){
return (low - first + 1);
}else{
return 0;
}
}
using STL we can find the index
vector<int> vec{1,2,3,4,5,6,7,8,9} ;
vector<int> :: iterator index;
index=lower_bound(vec.begin(),vec.end(),search_data);
return (index-vec.begin());
There is no simple STL method which returns index against a sorted vector as far as I know, however you can use sample function below:
/**
* @param v - sorted vector instance
* @param data - value to search
* @return 0-based index if data found, -1 otherwise
*/
int binary_search_find_index(std::vector<int> v, int data) {
auto it = std::lower_bound(v.begin(), v.end(), data);
if (it == v.end() || *it != data) {
return -1;
} else {
std::size_t index = std::distance(v.begin(), it);
return index;
}
}
int a = 0, b = n-1;
while (a <= b) {
int k = (a+b)/2;
if (array[k] == x)
{
// x found at index k
}
if (array[k] < x) a = k+1;
else b = k-1;
}
Clearly, this "will return the bitwise complement" is a big deal for you and I do not understand what you mean. That said, lookup std::upper_bound and see if it does what you want.