问题
What is the complexity of search in sorted std::list? I knew that complexity of search in sorted data is O(log n) if the data structure has random access. But since list doesn't have random access, what is it's complexity when it is sorted?
回答1:
Well, it's O(N). Search is always O(N) in a std::list
, sorted or not.
Sorted collections help because you can know if you're too far, or not enough. But since you can't start anywhere but at one end of a list, it won't help.
回答2:
It depends how you search. Given std::list<T> x
and a value v
that is not in the list,
std::find(x.begin(), x.end(), value)
is a linear search, so it will takex.size()
comparisons and iteration steps, andstd::binary_search(x.begin(), x.end())
performs binary search with O(log(x.size()
)) comparisons, but it will still have to increment iterators linearly to address the target of each comparison (and same forstd::lower_bound
etc.). The behaviour is undefined for this invocation if the list is not in sorted order.
Generally, iterator incrementing has a non-trivial cost for node-based containers, since it involves pointer chasing and is non-local in memory. However, you need to consider the cost of your value type's comparison operation (which could be high, e.g. for very long, almost equal strings). Moreover, you may be able to address memory locality by allocating nodes from a dedicated arena.
来源:https://stackoverflow.com/questions/26170743/what-is-the-complexity-of-search-in-sorted-stdlist