Priority Queue using heap
📚 What is a Priority Queue?
A Priority Queue is a special type of queue where:
-
Each element has a priority associated with it.
-
Elements with higher priority are served before elements with lower priority.
-
If two elements have the same priority, they are served according to their order in the queue (like normal queue behavior).
🔵 Important: It is not simply First-In-First-Out (FIFO) like a normal queue — instead, priority decides the order.
🎯 Example
Element | Priority |
---|---|
A | 2 |
B | 4 |
C | 1 |
-
B will be removed first (priority 4),
-
then A (priority 2),
-
then C (priority 1).
🔥 Real Life Examples
-
Operating systems scheduling processes (higher priority processes get CPU first)
-
Emergency rooms (patients with severe conditions are treated first)
-
Dijkstra’s algorithm for shortest path (priority by smallest distance)
🛠️ How to Implement Priority Queue?
There are different ways to implement a Priority Queue:
Method | Insert Time | Delete Time | Remarks |
---|---|---|---|
Unsorted Array/List | O(1) | O(n) | Fast insert, slow delete |
Sorted Array/List | O(n) | O(1) | Slow insert, fast delete |
Binary Heap (Best!) | O(log n) | O(log n) | Balanced insert and delete |
📚 Priority Queue using Binary Heap — Algorithms
1. Insert Operation (Heapify Up)
2. Find (Peek Highest Priority Element)
3. Delete Operation (Heapify Down)
🔥 Helper Functions
Heapify Up (for Insert)
(parent(index) = (index - 1) / 2)
Heapify Down (for Delete)
(left child = 2 × index + 1, right child = 2 × index + 2)
✨ Notes
-
Binary Heap maintains a complete binary tree structure.
-
Priority Queue with Binary Heap gives:
-
Insert → O(log n)
-
Delete Max → O(log n)
-
Find Max → O(1)
Comments
Post a Comment