Time Complexity of Java PriorityQueue (heap) insertion of n elements? [duplicate]

醉酒当歌 提交于 2019-12-10 13:14:58

问题


I would like to know what the time complexity of Java PriorityQueue.Add() is for n elements.

I understand that potential worse case insertion a single element is O(log(n)), but it is not clear to me what the time complexity is for inserting a collection of n elements?

I've seen claims from various sources (with no proofs) that the time to build a priority queue heap of n elements it is O(n), and have also seen claims that it is O(nlog(n)), which makes sense given insertion is O(log(n)), which multiplied n times would indeed equal O(nlog(n))

Note: I'm only interested in worse case, not amortized.

This question assumes there is a logical way to describe the act of populating a data structure (heap) with n elements, that is different than simply considering n x log(n) insertions individually.

I'm making no assumptions regarding the input (such as a bounds on the set of input values, or a partially ordered input).


回答1:


It is O(N log N) in the general case. An O(N) algorithm exists for the special case where the input is already ordered, but this isn't provided in java.util.PriorityQueue.




回答2:


It seems like the insertion of n elements should be O(n log n)

Java PriorityQueue (Java Doc)

O(log n) time for the enqueing and dequeing methods (offer, poll, remove() and add)

O(n) for the remove(Object) and contains(Object) methods

O(1) for the retrieval methods (peek, element, and size)

These time complexities seem all worst case (wiki), except for .add(). You are right to question the bounds as the Java Doc also states to the extension of this unbound structure:

The details of the growth policy are not specified

As they state in the Doc as well, the PriorityQueue is based on an array with a specific initial capacity. I would assume that the growth will cost O(n) time, which then would also be the worst case time complexity for .add().

To get a guaranteed O(n log n) time for adding n elements you may state the size of your n elements to omit extension of the container:

PriorityQueue(int initialCapacity)

EDIT: To the claim of O(n) time for construction is correct (as stated by @pjs in the comments). This procedure is often called heapify and works on an pre existing array that is used to construct a binary tree on it in O(n) time.



来源:https://stackoverflow.com/questions/47420638/time-complexity-of-java-priorityqueue-heap-insertion-of-n-elements

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