An abstract data type where each element has a priority. Common operations: insert,peek (view highest/lowest priority).delete / extract.Uses: CPU scheduling, Dijkstra’s algorithm, task scheduling, simulations.
Priority Queue &Heap
Sam Basil Fernand S
Assistant Professor- AIDS
Saveetha Engineering College,Chennai
2.
Priority Queue- AnIntroduction
•A Priority Queue is a specialized form of queue where each element is assigned a priority.
•Elements are processed based on priority, not strictly by the order of insertion.
•Unlike regular queues that follow the FIFO (First-In, First-Out) principle, priority queues
allow higher priority elements to be served first.
•The insertion time of an element does not affect when it is processed if another element has
higher priority.
•It is an abstract data structure that behaves like a queue but includes priority-based
removal of elements.
•Heap-Based Structure: Priority queues are often implemented using Min-Heap or Max-Heap
to efficiently retrieve the element with the highest priority.
•Flexible Implementations: They can also be implemented using Fibonacci Heaps, Balanced
BSTs, or sorted/unsorted arrays, depending on performance needs.
•Real-World Applications: Used in Dijkstra’s and Prim’s algorithms, CPU scheduling, event
simulations, and task prioritization systems.
•Behavior and Constraints: Prioritized insertion and retrieval; some implementations (e.g.,
Java's PriorityQueue) disallow null values and are not thread-safe by default.
3.
Key Characteristics:
•In aregular queue (like a line at a ticket counter), elements follow the First-In, First-Out (FIFO)
order—meaning the first element inserted is the first one removed.
•However, in a priority queue, elements with higher priority are always served before those with
lower priority, regardless of when they were added.
•Insertion: When a new element is added, it is placed not at the end but in a position that maintains
the priority ordering.
•Deletion: The element with the highest priority (or lowest, depending on the configuration) is
always removed first.
•In case of equal priority values, implementation-dependent rules (like insertion order or
comparator logic) decide which element is processed first.
Types of Priority Queue:
• Ascending Order Priority Queue : In this queue, elements with lower values have higher priority.
For example, with elements 4, 6, 8, 9, and 10, 4 will be dequeued first since it has the smallest
value, and the dequeue operation will return 4.
• Descending order Priority Queue : Elements with higher values have higher priority. The root of
the heap is the highest element, and it is dequeued first. The queue adjusts by maintaining the heap
property after each insertion or deletion.
5.
How Priority isDetermined in a Priority Queue?
• By Element Value (Default Behavior)
• Most standard implementations (like Java’s PriorityQueue) use element value directly to
decide priority.
• In a Min-Heap, lower values are dequeued first; in a Max-Heap, higher values have
higher priority.
• Custom Comparator (User-Defined Priority)
• You can define your own rules for priority using a Comparator (e.g., sort tasks by
deadline or severity).
• This is useful when elements are complex objects that don’t have natural ordering.
• Natural Ordering vs. Custom Logic
• If elements implement the Comparable interface, their compareTo() method is used for
priority.
• Custom logic using a Comparator overrides natural ordering and allows flexible sorting
behavior.
6.
Operations on aPriority Queue
1) Insertion
• When a new element is inserted into a priority queue, it must be placed in the correct position to
maintain the priority ordering.
• If using a heap-based implementation:
• The element is first added at the end of the heap (array).
• Then a heapify-up operation (also known as "bubble-up") is performed to restore the heap
property.
• In a Min-Heap, the element bubbles up if it is smaller than its parent; in a Max-Heap, if it is larger.
• Time Complexity: O(log n) for heap-based implementations.
2) Deletion (Remove/Dequeue)
• This operation typically removes the element with the highest priority (i.e., root of the heap).
• After removing the root:
• The last element in the heap is moved to the root position.
• A heapify-down (or "sift-down") operation is applied to maintain the priority order.
• This operation ensures the next highest priority element becomes accessible at the top.
• Time Complexity: O(log n).
7.
• 3) Peek(Top/Front)
• This operation returns the element with the highest priority without removing it from the queue.
• It simply accesses the root of the heap in a heap-based implementation.
• Useful for checking the current priority element at the front of the queue.
• Time Complexity: O(1) (constant time), as it involves just reading the root.
Comparison Table of Priority Queue Implementations
Data Structure
Insert (Enqueue /
Push)
Remove (Dequeue /
Pop)
Peek / Top Advantages Disadvantages
Array O(1) O(n) O(n)
Fast insertion. Simple
to implement.
Costly removal & peek
(need to scan for
highest priority).
Linked List O(n) O(1) O(1)
Quick deletion and
peek. Dynamic size
(no overflow).
Slower insertion due to
sorted order
maintenance.
Binary Heap O(log n) O(log n) O(1)
Optimal performance
for insert/delete. Used
in many real-world
applications.
Not ideal for search or
arbitrary deletion. Not
stable (equal
priorities).
Binary Search Tree O(log n) O(log n) O(1)
Maintains sorted order.
Good for range queries
and dynamic priorities.
Needs balancing (e.g.,
AVL/Red-Black Tree).
Overhead for
balancing operations.
8.
Sample Code
import java.util.*;
publicclass MinHeap {
private List<Integer> heap;
public MinHeap() {
heap = new ArrayList<>();
}
private int parent(int i) { return (i - 1) / 2; }
private int left(int i) { return 2 * i + 1; }
private int right(int i) { return 2 * i + 2; }
private void swap(int i, int j) {
int temp = heap.get(i);
heap.set(i, heap.get(j));
heap.set(j, temp);
}
public void insert(int val) {
9.
heap.add(val);
int i =heap.size() - 1;
while (i > 0 && heap.get(parent(i)) > heap.get(i)) {
swap(i, parent(i));
i = parent(i);
}
}
private void heapify(int i) {
int smallest = i;
int l = left(i);
int r = right(i);
if (l < heap.size() && heap.get(l) < heap.get(smallest)) smallest = l;
if (r < heap.size() && heap.get(r) < heap.get(smallest)) smallest = r;
if (smallest != i) {
swap(i, smallest);
heapify(smallest);
}}
10.
public int getMin(){
if (heap.isEmpty()) throw new NoSuchElementException("Heap is empty");
return heap.get(0);
}
public int extractMin() {
if (heap.isEmpty()) throw new NoSuchElementException("Heap is empty");
int min = heap.get(0);
int last = heap.remove(heap.size() - 1);
if (!heap.isEmpty()) {
heap.set(0, last);
heapify(0);
}
return min;
}
public void changePriority(int i, int newVal) {
if (i < 0 || i >= heap.size()) {
System.out.println("Invalid index");
return;
}
11.
int oldVal =heap.get(i);
heap.set(i, newVal);
if (newVal < oldVal) {
while (i > 0 && heap.get(parent(i)) > heap.get(i)) {
swap(i, parent(i));
i = parent(i);
}
} else {
heapify(i);
}
}
public void delete(int i) {
changePriority(i, Integer.MIN_VALUE);
extractMin();
}
public void printHeap() {
System.out.println("Current Heap: " + heap); }
12.
public static voidmain(String[] args) {
Scanner sc = new Scanner(System.in);
MinHeap h = new MinHeap();
while (true) {
System.out.println("n----- Min Heap Operations -----");
System.out.println("1. Insert");
System.out.println("2. Get Min");
System.out.println("3. Extract Min");
System.out.println("4. Change Priority");
System.out.println("5. Delete by Index");
System.out.println("6. Display Heap");
System.out.println("7. Exit");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter value to insert: ");
13.
int val =sc.nextInt();
h.insert(val);
break;
case 2:
try {
System.out.println("Minimum value: " + h.getMin());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 3:
try {
System.out.println("Extracted Min: " + h.extractMin());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
14.
case 4:
System.out.print("Enter indexto change: ");
int idx = sc.nextInt();
System.out.print("Enter new value: ");
int newVal = sc.nextInt();
h.changePriority(idx, newVal);
break;
case 5:
System.out.print("Enter index to delete: ");
int delIdx = sc.nextInt();
h.delete(delIdx);
break;
case 6:
h.printHeap();
break;
case 7:
System.out.println("Exiting...");
Advantages of PriorityQueue
•Quick Access to Highest Priority Element
•Efficient Dynamic Reordering of Elements
•Improves Performance in Graph/Search Algorithms
•Supports Real-Time and Scheduling Systems
•Flexible Implementation Options (Heaps, Trees, Lists)
•Thread-Safe Variants for Concurrent Environments
•Resource Prioritization and Fairness Control
•Customizable Priority Logic (Comparators)
•Enables Multi-Level Queue System Design
•Efficient for Event-Driven Simulations
•Reduces Complexity in Greedy Algorithms
•Useful in Load Balancing and Traffic Management
•Supports Bandwidth and Resource Allocation
•Used in Data Compression (e.g., Huffman Coding)
•Maintains Sorted Order Without Manual Sorting
17.
Disadvantages of PriorityQueue
• Complexity of Operations
• Not Suitable for FIFO Order
• No Direct Search
• Complex Implementation for Dynamic Priorities
• Increased Memory Usage
• Lack of Stability
• Thread-Safety Not Guaranteed
• Overhead in Maintaining Order
• Limited by Comparator Logic
• Difficult to Debug and Trace
• No Bulk Retrieval
• Starvation of Lower Priority Tasks
• Non-Intuitive Behavior
• Overhead in Maintaining Multiple Queues
18.
Applications of PriorityQueue
•Dijkstra’s Algorithm
•Prim’s Minimum Spanning Tree Algorithm
•A Pathfinding Algorithm*
•CPU Scheduling
•Task Scheduling in Operating Systems
•Huffman Coding (Data Compression)
•Bandwidth Management in Networks
•Event-Driven Simulation Systems
•Load Balancing Systems
•Print Queue Management
•Data Stream Processing
•Emergency Room Patient Management Systems
•Cache Eviction Policies (LFU)
•Real-Time Systems and Deadline Scheduling
•Job Scheduling in Cloud Computing
19.
Heap Data Structure-An Introduction
•Complete Binary Tree
•All levels are fully filled except possibly the last, which is filled from left to right.
•Ensures the tree is balanced, giving O(log n) height.
•Heap Property
•Max-Heap: The value of each parent node is greater than or equal to its children.
•Min-Heap: The value of each parent node is less than or equal to its children.
•Efficient Access to Extremes
•Max-Heap provides quick access to the maximum element.
•Min-Heap provides quick access to the minimum element.
•Accessing top element takes O(1) time.
•Efficient Insert and Delete Operations
•Insertion and deletion both take O(log n) time due to the need to maintain the heap property via
heapify operations.
•Array-Based Implementation
•Heaps are commonly implemented as arrays, where for any node at index i:
•Left child is at 2i + 1
•Right child is at 2i + 2
•Parent is at (i - 1) / 2
•This makes heap space-efficient and cache-friendly.
20.
Max and MinHeap
Max-heap:
The value of the root node must be the greatest
among all its descendant nodes and the same
thing must be done for its left and right sub-tree
also.
Min-heap:
The value of the root node must be the smallest
among all its descendant nodes and the same thing
must be done for its left and right sub-tree also.
21.
Similarities between Minand Max Heap:
Aspect Min Heap Max Heap Similarity
Tree Structure Complete binary tree Complete binary tree Both are complete binary trees
Heap Property Parent ≤ Children Parent ≥ Children
Enforce parent-child priority
relationship
Array Representation
Left: 2i + 1, Right: 2i + 2,
Parent: (i-1)/2
Same as Min Heap
Same index-based representation
in array
Insertion Time O(log n) O(log n) Identical insertion time
Deletion (Root) O(log n) O(log n) Identical deletion time
Peek (Root) O(1) O(1) Constant time access to root
Priority Queue Use Min-priority retrieval Max-priority retrieval
Both implement different types
of priority queues
Heapify Support Yes Yes Both support heapify operation
Sorting (Heap Sort) Ascending order Descending order
Both used in heap sort with
reverse roles
22.
Implementation of HeapData Structure
• The maxHeapify function is key to maintaining the Max-Heap property of a binary
heap. It ensures that a given node and its subtrees are arranged such that the parent
node is always greater than or equal to its children.
• Given an array arr[] that represents a complete binary tree:
• The left child of the node at index i is at 2*i + 1, and the right child is at 2*i + 2.
• Initially, we assume the current node i holds the maximum value.
• If the left child value (arr[2*i + 1]) is greater than arr[i], we update the maximum
index.
• Likewise, if the right child (arr[2*i + 2]) has a larger value than the current
maximum, we update the maximum index again.
• If the maximum has changed, we swap the current node with the larger child.
• This process is repeated recursively until the subtree rooted at index i satisfies the
Max-Heap property.
23.
Sample Code
import java.util.Scanner;
publicclass MaxHeap {
private int[] arr;
private int maxSize;
private int heapSize;
// Constructor
MaxHeap(int maxSize) {
this.maxSize = maxSize;
arr = new int[maxSize];
heapSize = 0;
}
// Heapify the subtree rooted at index i
void maxHeapify(int i) {
int left = leftChild(i);
int right = rightChild(i);
int largest = i;
if (left < heapSize && arr[left] > arr[largest]) {
largest = left;
}
24.
if (right <heapSize && arr[right] > arr[largest]) {
largest = right;
}
if (largest != i) {
swap(i, largest);
maxHeapify(largest);
} }
int parent(int i) {
return (i - 1) / 2; }
int leftChild(int i) {
return (2 * i + 1);
}
int rightChild(int i) {
return (2 * i + 2);
}
void swap(int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp; }
25.
void insertKey(int key){
if (heapSize == maxSize) {
System.out.println("Overflow: Could not insertKey");
return;
}
int i = heapSize++;
arr[i] = key;
while (i != 0 && arr[parent(i)] < arr[i]) {
swap(i, parent(i));
i = parent(i);
}
}
int getMax() {
return heapSize > 0 ? arr[0] : Integer.MIN_VALUE;
}
int removeMax() {
if (heapSize <= 0) return Integer.MIN_VALUE;
if (heapSize == 1) return arr[--heapSize];
int root = arr[0];
arr[0] = arr[--heapSize];
maxHeapify(0);
return root;
}
26.
void increaseKey(int i,int newVal) {
arr[i] = newVal;
while (i != 0 && arr[parent(i)] < arr[i]) {
swap(i, parent(i));
i = parent(i);
}}
void deleteKey(int i) {
if (i < 0 || i >= heapSize) {
System.out.println("Invalid index.");
return;
}
increaseKey(i, Integer.MAX_VALUE);
removeMax();
}
void printHeap() {
System.out.print("Heap elements: ");
for (int i = 0; i < heapSize; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
int curSize() {
return heapSize;}
27.
public static voidmain(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter maximum size of heap: ");
int size = sc.nextInt();
MaxHeap heap = new MaxHeap(size);
System.out.println("nChoose an operation:");
System.out.println("1: Insert");
System.out.println("2: Delete by Index");
System.out.println("3: Get Max");
System.out.println("4: Remove Max");
System.out.println("5: Print Heap");
System.out.println("6: Exit");
while (true) {
System.out.print("nEnter choice: ");
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter value to insert: ");
int val = sc.nextInt();
heap.insertKey(val);
break;
28.
case 2:
System.out.print("Enter indexto delete: ");
int index = sc.nextInt();
heap.deleteKey(index);
break;
case 3:
System.out.println("Maximum element: " + heap.getMax());
break;
case 4:
System.out.println("Removed max element: " + heap.removeMax());
break;
case 5:
heap.printHeap();
break;
case 6:
System.out.println("Exiting...");
sc.close();
return;
29.
default:
System.out.println("Invalid choice!");
}}}}
Advantages ofHeap:
• Time Efficiency: Heaps offer efficient performance for operations like insertion and deletion, both of which take
O(log n) time on average. Additionally, constructing a heap from an unsorted array can be done in O(n) time.
Most importantly, accessing the highest or lowest priority element (depending on the heap type) takes constant
time — O(1).
• Space Optimization: Because heaps are implemented as complete binary trees, they can be compactly
represented using arrays. This ensures no memory is wasted on unused tree nodes, making the structure space-
efficient.
• Dynamic Structure: Heaps support dynamic resizing as elements are added or removed, which makes them
ideal for applications where the data size changes frequently, such as real-time systems.
• Priority-Based Processing: Heaps are designed to handle elements based on priority levels. This makes them
valuable in scenarios where urgency or importance matters, such as task scheduling, traffic management,
healthcare monitoring systems, and stock market analytics.
• In-Place Rearrangement: Heaps are used in algorithms like Heap Sort, where elements are sorted in-place
without needing additional storage, leading to better memory utilization.
30.
Disadvantages of Heap
•LimitedFlexibility: Heaps strictly maintain order, making them less suitable for use cases requiring
dynamic or flexible data handling.
•Inefficient Searching: Finding a specific element in a heap requires scanning the entire structure (O(n)),
which is not optimal for search operations.
•Not Stable: Equal-priority elements may not retain their insertion order, as heaps do not guarantee stability.
•Potential Overhead: Although insertions and deletions are efficient, worst-case scenarios (like repeated
operations on large data) can result in O(n log n) time, which may be too slow for certain performance-critical
applications.
Applications of Heap:
• Priority Queues
• Sorting Algorithms (Heapsort)
• Graph Algorithms (Prim’s, Dijkstra’s, A*)
• Lossless Compression (Huffman Coding)
• Medical Applications
• Load Balancing
• Order Statistics (kth smallest/largest)
• Resource Allocation
• Job Scheduling