Week 73 — What is a `PriorityQueue` and how does it differ from regular `Queue`s?
Question of the Week #73
What is a
PriorityQueue
and how does it differ from regular Queue
s?6 Replies
A
Queue
typically allows elements to be inserted and retrieved in the order of insertion.
On the other hand, a PriorityQueue
allows inserting elements and then always retrieving the smallest element.
However, it should be noted that the elements in a PriorityQueue
are not sorted. While it ensures that polling/removing the head always accesses the smallest element, iterating over all elements may not result in the elements being sorted. In fact, PriorityQueue
does not have any guaranteed iteration order. Retrieving the elements of a PriorityQueue
in order requires removing them one after each other.
Internally, PriorityQueue
uses an array-based MinHeap.📖 Sample answer from dan1st
PriorityQueue is a kind of queue where the rule of element being dequeue is determined by the maximum or minimum priority value each element has. Different from regular queue, which the element being dequeue is based on FIFO (First-In-First-Out) characteristic.
Submission from .brutallus
hello , pq is an ordered containersorts ur data in ascending and if u want descending order insertion and removal takes O(logn ) of time queue is a container with unordered data the top of pq is the element with the highest value or lowest value depending on ur implementation while queue is the first inserted element
Submission from gonzothegovernment
Priority Queue are the queue which are serve basis on their priority, means if the data is entered in queue then they can be be accesed according to their priority not sequence number.
In priority queue a priority number has been set while entering the data.
Submission from chandrashekhar_
A priority Queue in Java is a data structure that orders it's elements according to their priority, with the highest-priority element always at the front of the queue. It is implemented using a heap data structure. On the other hand, a regular Queue in Java follows the First-In-First-Out (FIFO) principle, where the first element added to the queue is the first one to be removed.
Submission from techstack_joyel
Normal Queue which obeys the rule that the order in which consumers take element from the queues is the same as producers produces element into it(FIFO, such as LinkedBlockingQueue/ArrayBlockingQueue). It is impossible for a producer to cut in line(based on priority) while producing elements,
However, PriorityQueue can easily do this, we can specify a priority(usually ranging from 1 to 10) for elements as they sent. In this way, the consumer can automaticlly take the highest priority elements.
Submission from wzq1008