Complexity of PriorityQueue addAll()
Asked Answered
A

4

11

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?

Astroid answered 14/1, 2013 at 1:10 Comment(0)
J
9

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.

Julio answered 14/1, 2013 at 1:15 Comment(2)
...? O(m log n), not O(m n log n).Luthuli
I think it would be O(m log(n+m)). Think about case when n=0Veridical
L
3

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.

Lout answered 14/1, 2013 at 1:17 Comment(0)
K
2

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

Keturahkeung answered 14/1, 2013 at 1:16 Comment(0)
C
0

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
Colossal answered 14/7, 2022 at 20:1 Comment(1)
That is true, but then it uses natural ordering (so min heap for Ints). Is there a way to run heapify with a custom comparator?Broglie

© 2022 - 2024 — McMap. All rights reserved.