Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary search with returned index in STL?

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.

like image 336
liran63 Avatar asked Dec 11 '14 19:12

liran63


People also ask

Is there an STL for binary search?

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.

What does Binary_search return in C++?

binary_search(start_ptr, end_ptr, num): This function returns true if the element is present in the container, else returns false.

Is there a built in binary search in C++?

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.

What is lower bound binary search?

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.


2 Answers

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).
  • Both will return an iterator to the next larger item if the specified value isn't present (or .last() if there is no larger item).
like image 85
Jerry Coffin Avatar answered Sep 21 '22 04:09

Jerry Coffin


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;
    }   
}
like image 25
Jonathan L Avatar answered Sep 22 '22 04:09

Jonathan L