Does binary search have logarithmic performance of deque C++ data structure?

隐身守侯 提交于 2019-12-24 11:06:38

问题


The standard says that std::binary_search(...) and the two related functions std::lower_bound(...) and std::upper_bound(...) are O(log n) if the data structure has random access. So, given that, I presume that these algorithms have O(log n) performance on std::deque (assuming its contents are kept sorted by the user).

However, it seems that the internal representation of std::deque is tricky (it's broken into chunks), so I was wondering: does the requirement of O(log n) search hold for std::deque.


回答1:


Yes it still holds for deque because the container is required to provide access to any element in constant time (just a slightly higher constant than vector).

That doesn't relieve you of the obligation for the deque to be sorted though.




回答2:


Yes. deque has constant time access for an index if it is there. It is organized in pages of an equal size. What you have is smth. like a vector of pointers to pages. If you have let's say 2 pages with 100 elements and you would like to access 103rd element than determine the page by 103/100 = 1 and determine the index in the page by 103 %100 => 3. Now use a constant time access in two vectors to get the element.

Here the statement from http://www.cplusplus.com/reference/stl/deque/:

Deques may be implemented by specific libraries in different ways, but in all cases they allow for the individual elements to be accessed through random access iterators, with storage always handled automatically (expanding and contracting as needed).




回答3:


Just write a program to test that, I think deque's implementation of binary_search will slower than vector's, but it's complexity is still O(logn)



来源:https://stackoverflow.com/questions/6455541/does-binary-search-have-logarithmic-performance-of-deque-c-data-structure

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