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, will return the bitwise complement of the index of the next element that is larger than the item I looked for.
What is the function I am looking for?
Edit: I need to insert an item to a sorted vector and to keep it sorted. That's why I need to bitwise complement index.
Binary Search functions in C++ STL (binary_search, lower_bound and upper_bound) Binary search is a search algorithm that searches for an element by comparing it with the middle value of the array and dividing it based on the value. The algorithm does this repeatedly until the element is found.
binary_search(start_ptr, end_ptr, num): This function returns true if the element is present in the container, else returns false.
The bsearch() function in C++ performs a binary search of an element in an array of elements and returns a pointer to the element if found. The bsearch() function requires all elements less than the element to be searched to the left of it in the array.
The lower and upper bound of a binary search are the lowest and highest position where the value could be inserted without breaking the ordering.
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 if the value wasn't found.
lower_bound
will find the position of the first item with that value (if any).upper_bound
will find the position of the last item with that value (again, if any)..last()
if there is no larger item).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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With