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)
Example: Insert 50 into a Max-Heap
Initial Max-Heap (array):
[40, 30, 15, 10, 20]
Tree form:
Step 1: Insert new element 50 at the end
Array = [40, 30, 15, 10, 20, 50]
Tree form:
Step 2: Heapify Up (compare 50 with parent 15)
-
50 > 15 → swap
Array = [40, 30, 50, 10, 20, 15]
Tree:
Step 3: Continue Heapify Up (compare 50 with parent 40)
-
50 > 40 → swap
Array = [50, 30, 40, 10, 20, 15]
Tree:
✅ Final Max-Heap:
Array = [50, 30, 40, 10, 20, 15]
Tree:
👉 This clearly shows Heapify Up (Bubble Up): the inserted element (50) keeps moving upward until the heap property is restored.
Heapify Down (for Delete)
(left child = 2 × index + 1, right child = 2 × index + 2)
Example: Heapify Down after Deleting Root
Initial Max-Heap:
Array representation: [50, 30, 40, 10, 20]
Step 1: Delete root (50)
-
Replace root with last element (20)
-
Heap =
[20, 30, 40, 10]
Step 2: Heapify Down from root (20)
-
Compare 20 with children (30, 40)
-
Largest child = 40
-
Swap 20 ↔ 40
Heap = [40, 30, 20, 10]
Step 3: Continue Heapify Down at node (20)
-
Children of 20: none (leaf node)
-
Stop
Final Max-Heap:
Array: [40, 30, 20, 10]
👉 This example demonstrates Heapify Down: after removing the root, the new root is pushed down until the heap property is restored.
✨ 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