![]() |
VOOZH | about |
A priority queue is a type of queue where each element is associated with a priority value, and elements are served based on their priority rather than their insertion order.
The binary heap is the most common implementation of a priority queue:
Priority queues are widely used in algorithms such as Dijkstraโs shortest path algorithm, Primโs minimum spanning tree algorithm, and Huffman coding for data compression.
Since the heap is maintained in the form of a complete binary tree, so it can be represented in the form of an array. To keep the tree complete and shallow, while inserting a new element insert it in the leftmost vacant position in the last level i.e., at the end of our array. Similarly, while extracting maximum replace the root with the last leaf at the last level i.e., the last element of the array.
A Binary Heap is ideal for priority queue implementation as it offers better performance The largest key is at the top and can be removed in O(log n) time, with the heap property restored efficiently. If a new entry is inserted immediately, its O(log n) insertion time may overlap with restoration. Since heaps use contiguous storage, they efficiently handle large datasets while ensuring logarithmic time for insertions and deletions.
Time Complexity: O(log n), for all the operation, except getMax(), which has time complexity of O(1).
Space Complexity: O(n)
There is no priority attached to elements in a queue, the rule of first-in-first-out(FIFO) is implemented whereas, in a priority queue, the elements have a priority. The elements with higher priority are served first.
A typical priority queue supports the following operations:
1) Insertion (push) : When a new item is inserted in a Max-Heap, if it has the highest value, it becomes the root; in a Min-Heap, if it has the smallest value, it becomes the root. Otherwise, it is placed so that all higher-priority elements (larger in Max-Heap, smaller in Min-Heap) are accessed before it.
2) Deletion(pop) : We usually remove the highest-priority item, which is always at the top. After removing it, the next highest-priority item automatically takes its place at the top.
3) top : This operation only returns the highest priority item (which is typically available at the top) and does not make any change to the priority queue.