When we code and use a priority queue, what exactly does priority stand for? Is it something abstract or is it something concrete, such as sorting per height of different buildings? What is the advantage of using a priority queue?
A plain queue deals with items on a first-come-first-served basis. Priority queues determine a service order based on the priorities of the items. With a priority queue the next item to be dealt with will be the one with the highest priority ranking.
Examples:
This is something concrete, it determines the actual operations of a system. Your job as a programmer is to identify and reflect that real-world behavior by supplying an ordering property. In Java this is done by making the objects Comparable
or supplying a Comparator
.
You can define the priority by letting the elements implement Comparable
interface and offering a Comparator
to construct the queue, see the doc:
The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With