Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use a TreeMap over a PriorityQueue and vice versa?

Seems they both let you retrieve the minimum, which is what I need for Prim's algorithm, and force me to remove and reinsert a key to update its value. Is there any advantage of using one over the other, not just for this example, but generally speaking?

like image 672
iceburn Avatar asked Aug 19 '10 18:08

iceburn


People also ask

What is the difference between PriorityQueue and TreeSet in Java?

TreeSet uses the Set underlying data structure. In PriorityQueue, apart from the root rest of the elements may or may not follow any order. In TreeSet all the elements remain in the sorted order. Using PriorityQueue, we can retrieve largest or smallest element in O(1) time.

Is a PriorityQueue always sorted?

A PriorityQueue is what is called a binary heap. It is only ordered/sorted in the sense that the first element is the least. In other word, it only cares about what is in the front of the queue, the rest are "ordered" when needed.

What is the time complexity of PriorityQueue?

It will take O(log N) time to insert and delete each element in the priority queue. Based on heap structure, priority queue also has two types max- priority queue and min - priority queue. Let's focus on Max Priority Queue.

Is PriorityQueue Min or Max?

The default PriorityQueue is implemented with Min-Heap, that is the top element is the minimum one in the heap.


1 Answers

Generally speaking, it is less work to track only the minimum element, using a heap.

A tree is more organized, and it requires more computation to maintain that organization. But if you need to access any key, and not just the minimum, a heap will not suffice, and the extra overhead of the tree is justified.

like image 104
erickson Avatar answered Oct 14 '22 08:10

erickson