Which function is more efficient in searching an element in vector find() or binary_search() ?
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):
std::find()
std::binary_search()
std::set
, std::map
or their unordered counterparts also consider their builtin methods like std::set::find