Search code examples
c++stlbinary-search

find() vs binary_search() in STL


Which function is more efficient in searching an element in vector find() or binary_search() ?


Solution

  • The simple answer is: std::find for unsorted data and std::binary_search for sorted data. But I think there's much more to this:

    Both methods take a range [start, end) with n elements and and a value x that is to be found as input. But note the important difference that std::binary_search only returns a bool that tells you wether the range contained the element, or not. std::find() returns an iterator. So both have different, but overlapping use cases.


    std::find() is pretty straight forward. O(n) iterator increments and O(n) comparisons. Also it doesn't matter wether the input data is sorted or not.


    For std::binary_search() you need to consider multiple factors:

    • It only works on sorted data. You need to take the cost of sorting into account.

    • The number of comparisons is always O(log n).

    • If the iterator does not satisfy LegacyRandomAccessIterator the number of iterator increments is O(n), it will be logarithmic when they do satisfy this requirement.


    Conclusion (a bit opinionated):

    • when you operate on un-sorted data or need the location of the item you searched for you must use std::find()
    • when your data is already sorted or needs to be sorted anyway and you simply want to check if an element is present or not, use std::binary_search()
    • If you want to search containers like std::set, std::map or their unordered counterparts also consider their builtin methods like std::set::find