简体   繁体   中英

Complexity of PriorityQueue addAll()

What is the complexity of the addAll method of PriorityQueue. Does it add one element at a time resulting in O(n log n) or does it use a build heap process that creates a heap out of unordered elements in O(n) time?

Javadoc seems to imply that addAll is inherited from AbstractQueue where it is implemented as a sequence of adds .

This leads me to believe that the complexity is O(mlogn) where m is the size of the collection being inserted.

From Priority Queue

... this implementation provides O(log(n)) time for the enqueing and dequeing methods ...

So you can only assume n log(n) .

However - obviously - this is only what you can assume. Depending on the specific implementation you plan to use you may find some tricks that could improve matters for you.

Looking at the OpenJDK, it looks like PriorityQueue inherits the addAll implementation from AbstractQueue which iterates over the collection and calls add on each element.

Source

The addAll method in PriorityQueue implements add method for every element. Hence it has the time complexity of nlogn .

But this doesn't mean there is nothing equivalent to python's heapq.heapify() or C++ make_heap method that run in O(n) complexity. The PriorityQueue has the constructor that does the heapify operation with O(n) complexity.

List<Integer> x = Arrays.asList(1, 54, 22, 87, 242, 32, 11, 90);
PriorityQueue<Integer> pq1 = new PriorityQueue<Integer>(x); // O(n) complexity

PriorityQueue<Integer> pq2 = new PriorityQueue<Integer>();
pq2.addAll(x); // nlogn complexity

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM