Heaps
Heaps
• A priority queue is similar to a queue in which an item is dequeued (or removed) from
the front.
• However, unlike a regular queue, in a priority queue the logical order of elements is
determined by their priority.
• While the higher priority elements are added at the front of the queue, elements with
lower priority are added at the rear.
• Conceptually, we can think of a priority queue as a bag of priorities shown in Fig.
12.11.
• In this bag you can insert any priority but you can take out one with the highest value.
• Though we can easily implement priority queues using a linear array, but we should
first consider the time required to insert an element in the array and then sort it.
• We need O(n) time to insert an element and at least O(n log n) time to sort the array.
• Therefore, a better way to implement a priority queue is by using a binary heap which
allows both enqueue and dequeue of elements in O(log n) time.