What is the complexity of search in sorted std::list?

99封情书 提交于 2021-02-10 15:43:19

问题


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 take x.size() comparisons and iteration steps, and

  • std::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 for std::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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!