Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 876
user1908488 Avatar asked Jan 14 '13 01:01

user1908488


People also ask

What is the time complexity of the method offer () in the class PriorityQueue?

Answer: Time complexity for the methods offer & poll is O(log(n)) and for the peek() it is Constant time O(1) of java priority queue. SIDE NOTE: In Java programming, Java Priority Queue is implemented using Heap Data Structures, and Heap has O(log(n)) time complexity to insert and delete element.

What is the time complexity of building a priority queue?

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.)

What is PriorityQueue in Java?

A priority queue in Java is a special type of queue wherein all the elements are ordered as per their natural ordering or based on a custom Comparator supplied at the time of creation.

What is the time complexity of deleting an element from a priority queue is?

The complexity for remove is O(N) since the complexity for contains is O(N) (in java's priority queue class)


2 Answers

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.

like image 54
Karthik T Avatar answered Sep 20 '22 07:09

Karthik T


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.

like image 24
OldCurmudgeon Avatar answered Sep 21 '22 07:09

OldCurmudgeon