What is the time complexity of constructing a PriorityQueue from a collection?

微笑、不失礼 提交于 2019-11-29 10:48:52
Stuart Marks

The time complexity to initialize a PriorityQueue from a collection, even an unsorted one, is O(n). Internally this uses a procedure called siftDown() to "heapify" an array in-place. (This is also called pushdown in the literature.)

This is counterintuitive. It seems like inserting an element into a heap is O(log n) so inserting n elements results in O(n log n) complexity. This is true if you insert the elements one at a time. (Internally, inserting an individual element does this using siftUp().)

Heapifying an individual element is certainly O(log n), but the "trick" of siftDown() is that as each element is processed, the number of elements that it has to be sifted past is continually decreasing. So the total complexity isn't n elements times log(n); it's the sum of n terms of the decreasing cost of sifting past the remaining elements.

See this answer, and see also this article that works through the math.

The complexity can't be O(log(n)) because to process n elements, the complexity has to be at least O(n).

However, the PriorityQueue(Collection c) constructor checks whether the collection is a SortedSet, a PriorityQueue or a normal Collection and performs the initialization differently. If the parameter is a SortedSet or a PriorityQueue the complexity is O(n) (it's implemented as an array copy). When using another Collection it looks to be O(n log(n)).

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