Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std:find() for sorted vs unsorted

Tags:

c++

algorithm

std

Consider two integer vectors v1 and v2, where v1 is sorted and v2 is not sorted. What would be the time complexities to search for an element in these two vectors using find()?

like image 520
user123 456 Avatar asked Mar 11 '26 15:03

user123 456


1 Answers

std::find() performs linear search, i.e., it goes element by element until it finds the value it's looking for. It is linear regardless of whether or not the collection is sorted.

If you have a sorted vector, you may want to consider performing binary search with std::lower_bound() instead. This will be logarithmic in the size of the vector.

like image 179
ネロク・ゴ Avatar answered Mar 14 '26 05:03

ネロク・ゴ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!