- Blog Categories
- Software Development Projects and Ideas
- 12 Computer Science Project Ideas
- 28 Beginner Software Projects
- Top 10 Engineering Project Ideas
- Top 10 Easy Final Year Projects
- Top 10 Mini Projects for Engineers
- 25 Best Django Project Ideas
- Top 20 MERN Stack Project Ideas
- Top 12 Real Time Projects
- Top 6 Major CSE Projects
- 12 Robotics Projects for All Levels
- Java Programming Concepts
- Abstract Class in Java and Methods
- Constructor Overloading in Java
- StringBuffer vs StringBuilder
- Java Identifiers: Syntax & Examples
- Types of Variables in Java Explained
- Composition in Java: Examples
- Append in Java: Implementation
- Loose Coupling vs Tight Coupling
- Integrity Constraints in DBMS
- Different Types of Operators Explained
- Career and Interview Preparation in IT
- Top 14 IT Courses for Jobs
- Top 20 Highest Paying Languages
- 23 Top CS Interview Q&A
- Best IT Jobs without Coding
- Software Engineer Salary in India
- 44 Agile Methodology Interview Q&A
- 10 Software Engineering Challenges
- Top 15 Tech's Daily Life Impact
- 10 Best Backends for React
- Cloud Computing Reference Models
- Web Development and Security
- Find Installed NPM Version
- Install Specific NPM Package Version
- Make API Calls in Angular
- Install Bootstrap in Angular
- Use Axios in React: Guide
- StrictMode in React: Usage
- 75 Cyber Security Research Topics
- Top 7 Languages for Ethical Hacking
- Top 20 Docker Commands
- Advantages of OOP
- Data Science Projects and Applications
- 42 Python Project Ideas for Beginners
- 13 Data Science Project Ideas
- 13 Data Structure Project Ideas
- 12 Real-World Python Applications
- Python Banking Project
- Data Science Course Eligibility
- Association Rule Mining Overview
- Cluster Analysis in Data Mining
- Classification in Data Mining
- KDD Process in Data Mining
- Data Structures and Algorithms
- Binary Tree Types Explained
- Binary Search Algorithm
- Sorting in Data Structure
- Binary Tree in Data Structure
- Binary Tree vs Binary Search Tree
- Recursion in Data Structure
- Data Structure Search Methods: Explained
- Binary Tree Interview Q&A
- Linear vs Binary Search
- Priority Queue Overview
- Python Programming and Tools
- Top 30 Python Pattern Programs
- List vs Tuple
- Python Free Online Course
- Method Overriding in Python
- Top 21 Python Developer Skills
- Reverse a Number in Python
- Switch Case Functions in Python
- Info Retrieval System Overview
- Reverse a Number in Python
- Real-World Python Applications
- Data Science Careers and Comparisons
- Data Analyst Salary in India
- Data Scientist Salary in India
- Free Excel Certification Course
- Actuary Salary in India
- Data Analyst Interview Guide
- Pandas Interview Guide
- Tableau Filters Explained
- Data Mining Techniques Overview
- Data Analytics Lifecycle Phases
- Data Science Vs Analytics Comparison
- Artificial Intelligence and Machine Learning Projects
- Exciting IoT Project Ideas
- 16 Exciting AI Project Ideas
- 45+ Interesting ML Project Ideas
- Exciting Deep Learning Projects
- 12 Intriguing Linear Regression Projects
- 13 Neural Network Projects
- 5 Exciting Image Processing Projects
- Top 8 Thrilling AWS Projects
- 12 Engaging AI Projects in Python
- NLP Projects for Beginners
- Concepts and Algorithms in AIML
- Basic CNN Architecture Explained
- 6 Types of Regression Models
- Data Preprocessing Steps
- Bagging vs Boosting in ML
- Multinomial Naive Bayes Overview
- Gini Index for Decision Trees
- Bayesian Network Example
- Bayes Theorem Guide
- Top 10 Dimensionality Reduction Techniques
- Neural Network Step-by-Step Guide
- Technical Guides and Comparisons
- Make a Chatbot in Python
- Compute Square Roots in Python
- Permutation vs Combination
- Image Segmentation Techniques
- Generative AI vs Traditional AI
- AI vs Human Intelligence
- Random Forest vs Decision Tree
- Neural Network Overview
- Perceptron Learning Algorithm
- Selection Sort Algorithm
- Career and Practical Applications in AIML
- AI Salary in India Overview
- Biological Neural Network Basics
- Top 10 AI Challenges
- Production System in AI
- Top 8 Raspberry Pi Alternatives
- Top 8 Open Source Projects
- 14 Raspberry Pi Project Ideas
- 15 MATLAB Project Ideas
- Top 10 Python NLP Libraries
- Naive Bayes Explained
- Digital Marketing Projects and Strategies
- 10 Best Digital Marketing Projects
- 17 Fun Social Media Projects
- Top 6 SEO Project Ideas
- Digital Marketing Case Studies
- Coca-Cola Marketing Strategy
- Nestle Marketing Strategy Analysis
- Zomato Marketing Strategy
- Monetize Instagram Guide
- Become a Successful Instagram Influencer
- 8 Best Lead Generation Techniques
- Digital Marketing Careers and Salaries
- Digital Marketing Salary in India
- Top 10 Highest Paying Marketing Jobs
- Highest Paying Digital Marketing Jobs
- SEO Salary in India
- Brand Manager Salary in India
- Content Writer Salary Guide
- Digital Marketing Executive Roles
- Career in Digital Marketing Guide
- Future of Digital Marketing
- MBA in Digital Marketing Overview
- Digital Marketing Techniques and Channels
- 9 Types of Digital Marketing Channels
- Top 10 Benefits of Marketing Branding
- 100 Best YouTube Channel Ideas
- YouTube Earnings in India
- 7 Reasons to Study Digital Marketing
- Top 10 Digital Marketing Objectives
- 10 Best Digital Marketing Blogs
- Top 5 Industries Using Digital Marketing
- Growth of Digital Marketing in India
- Top Career Options in Marketing
- Interview Preparation and Skills
- 73 Google Analytics Interview Q&A
- 56 Social Media Marketing Q&A
- 78 Google AdWords Interview Q&A
- Top 133 SEO Interview Q&A
- 27+ Digital Marketing Q&A
- Digital Marketing Free Course
- Top 9 Skills for PPC Analysts
- Movies with Successful Social Media Campaigns
- Marketing Communication Steps
- Top 10 Reasons to Be an Affiliate Marketer
- Career Options and Paths
- Top 25 Highest Paying Jobs India
- Top 25 Highest Paying Jobs World
- Top 10 Highest Paid Commerce Job
- Career Options After 12th Arts
- Top 7 Commerce Courses Without Maths
- Top 7 Career Options After PCB
- Best Career Options for Commerce
- Career Options After 12th CS
- Top 10 Career Options After 10th
- 8 Best Career Options After BA
- Projects and Academic Pursuits
- 17 Exciting Final Year Projects
- Top 12 Commerce Project Topics
- Top 13 BCA Project Ideas
- Career Options After 12th Science
- Top 15 CS Jobs in India
- 12 Best Career Options After M.Com
- 9 Best Career Options After B.Sc
- 7 Best Career Options After BCA
- 22 Best Career Options After MCA
- 16 Top Career Options After CE
- Courses and Certifications
- 10 Best Job-Oriented Courses
- Best Online Computer Courses
- Top 15 Trending Online Courses
- Top 19 High Salary Certificate Courses
- 21 Best Programming Courses for Jobs
- What is SGPA? Convert to CGPA
- GPA to Percentage Calculator
- Highest Salary Engineering Stream
- 15 Top Career Options After Engineering
- 6 Top Career Options After BBA
- Job Market and Interview Preparation
- Why Should You Be Hired: 5 Answers
- Top 10 Future Career Options
- Top 15 Highest Paid IT Jobs India
- 5 Common Guesstimate Interview Q&A
- Average CEO Salary: Top Paid CEOs
- Career Options in Political Science
- Top 15 Highest Paying Non-IT Jobs
- Cover Letter Examples for Jobs
- Top 5 Highest Paying Freelance Jobs
- Top 10 Highest Paying Companies India
- Career Options and Paths After MBA
- 20 Best Careers After B.Com
- Career Options After MBA Marketing
- Top 14 Careers After MBA In HR
- Top 10 Highest Paying HR Jobs India
- How to Become an Investment Banker
- Career Options After MBA - High Paying
- Scope of MBA in Operations Management
- Best MBA for Working Professionals India
- MBA After BA - Is It Right For You?
- Best Online MBA Courses India
- MBA Project Ideas and Topics
- 11 Exciting MBA HR Project Ideas
- Top 15 MBA Project Ideas
- 18 Exciting MBA Marketing Projects
- MBA Project Ideas: Consumer Behavior
- What is Brand Management?
- What is Holistic Marketing?
- What is Green Marketing?
- Intro to Organizational Behavior Model
- Tech Skills Every MBA Should Learn
- Most Demanding Short Term Courses MBA
- MBA Salary, Resume, and Skills
- MBA Salary in India
- HR Salary in India
- Investment Banker Salary India
- MBA Resume Samples
- Sample SOP for MBA
- Sample SOP for Internship
- 7 Ways MBA Helps Your Career
- Must-have Skills in Sales Career
- 8 Skills MBA Helps You Improve
- Top 20+ SAP FICO Interview Q&A
- MBA Specializations and Comparative Guides
- Why MBA After B.Tech? 5 Reasons
- How to Answer 'Why MBA After Engineering?'
- Why MBA in Finance
- MBA After BSc: 10 Reasons
- Which MBA Specialization to choose?
- Top 10 MBA Specializations
- MBA vs Masters: Which to Choose?
- Benefits of MBA After CA
- 5 Steps to Management Consultant
- 37 Must-Read HR Interview Q&A
- Fundamentals and Theories of Management
- What is Management? Objectives & Functions
- Nature and Scope of Management
- Decision Making in Management
- Management Process: Definition & Functions
- Importance of Management
- What are Motivation Theories?
- Tools of Financial Statement Analysis
- Negotiation Skills: Definition & Benefits
- Career Development in HRM
- Top 20 Must-Have HRM Policies
- Project and Supply Chain Management
- Top 20 Project Management Case Studies
- 10 Innovative Supply Chain Projects
- Latest Management Project Topics
- 10 Project Management Project Ideas
- 6 Types of Supply Chain Models
- Top 10 Advantages of SCM
- Top 10 Supply Chain Books
- What is Project Description?
- Top 10 Project Management Companies
- Best Project Management Courses Online
- Salaries and Career Paths in Management
- Project Manager Salary in India
- Average Product Manager Salary India
- Supply Chain Management Salary India
- Salary After BBA in India
- PGDM Salary in India
- Top 7 Career Options in Management
- CSPO Certification Cost
- Why Choose Product Management?
- Product Management in Pharma
- Product Design in Operations Management
- Industry-Specific Management and Case Studies
- Amazon Business Case Study
- Service Delivery Manager Job
- Product Management Examples
- Product Management in Automobiles
- Product Management in Banking
- Sample SOP for Business Management
- Video Game Design Components
- Top 5 Business Courses India
- Free Management Online Course
- SCM Interview Q&A
- Fundamentals and Types of Law
- Acceptance in Contract Law
- Offer in Contract Law
- 9 Types of Evidence
- Types of Law in India
- Introduction to Contract Law
- Negotiable Instrument Act
- Corporate Tax Basics
- Intellectual Property Law
- Workmen Compensation Explained
- Lawyer vs Advocate Difference
- Law Education and Courses
- LLM Subjects & Syllabus
- Corporate Law Subjects
- LLM Course Duration
- Top 10 Online LLM Courses
- Online LLM Degree
- Step-by-Step Guide to Studying Law
- Top 5 Law Books to Read
- Why Legal Studies?
- Pursuing a Career in Law
- How to Become Lawyer in India
- Career Options and Salaries in Law
- Career Options in Law India
- Corporate Lawyer Salary India
- How To Become a Corporate Lawyer
- Career in Law: Starting, Salary
- Career Opportunities: Corporate Law
- Business Lawyer: Role & Salary Info
- Average Lawyer Salary India
- Top Career Options for Lawyers
- Types of Lawyers in India
- Steps to Become SC Lawyer in India
- Tutorials
- C Tutorials
- Recursion in C: Fibonacci Series
- Checking String Palindromes in C
- Prime Number Program in C
- Implementing Square Root in C
- Matrix Multiplication in C
- Understanding Double Data Type
- Factorial of a Number in C
- Structure of a C Program
- Building a Calculator Program in C
- Compiling C Programs on Linux
- Java Tutorials
- Handling String Input in Java
- Determining Even and Odd Numbers
- Prime Number Checker
- Sorting a String
- User-Defined Exceptions
- Understanding the Thread Life Cycle
- Swapping Two Numbers
- Using Final Classes
- Area of a Triangle
- Skills
- Software Engineering
- JavaScript
- Data Structure
- React.js
- Core Java
- Node.js
- Blockchain
- SQL
- Full stack development
- Devops
- NFT
- BigData
- Cyber Security
- Cloud Computing
- Database Design with MySQL
- Cryptocurrency
- Python
- Digital Marketings
- Advertising
- Influencer Marketing
- Search Engine Optimization
- Performance Marketing
- Search Engine Marketing
- Email Marketing
- Content Marketing
- Social Media Marketing
- Display Advertising
- Marketing Analytics
- Web Analytics
- Affiliate Marketing
- MBA
- MBA in Finance
- MBA in HR
- MBA in Marketing
- MBA in Business Analytics
- MBA in Operations Management
- MBA in International Business
- MBA in Information Technology
- MBA in Healthcare Management
- MBA In General Management
- MBA in Agriculture
- MBA in Supply Chain Management
- MBA in Entrepreneurship
- MBA in Project Management
- Management Program
- Consumer Behaviour
- Supply Chain Management
- Financial Analytics
- Introduction to Fintech
- Introduction to HR Analytics
- Fundamentals of Communication
- Art of Effective Communication
- Introduction to Research Methodology
- Mastering Sales Technique
- Business Communication
- Fundamentals of Journalism
- Economics Masterclass
- Free Courses
Priority Queue in Data Structure: Characteristics, Types & Implementation
Updated on 19 November, 2024
58.89K+ views
• 14 min read
Table of Contents
How do Google Maps find the fastest route to your destination? It uses a priority queue in data structure to make this possible. For instance, Dijkstra’s Shortest Path algorithm uses a min priority queue to rank all possible paths based on their distance. The path with the highest priority, often the shortest, is chosen as the best route.
A priority queue is a special data structure that processes elements based on their priority instead of the order they are added. This makes it different from a regular queue and incredibly useful in applications like navigation, task scheduling, and more.
In this blog, we’ll explore:
- What makes priority queues unique.
- The types of priority queues data structure.
- How to implement them step by step.
Let’s understand why priority queues are so important in solving real-world problems!
Check out: Free Python Course with Certification
What is a Priority Queue in Data Structure?
A priority queue is an abstract data type (ADT) that organizes elements based on their priority rather than the order in which they were added. Unlike a regular queue, which follows a first-in-first-out (FIFO) order, a priority queue processes the element with the highest priority first. This makes it a versatile tool for handling scenarios where priority matters more than sequence.
Example Behavior
Let’s consider a priority queue with values 1, 3, 4, 8, 14, 22 arranged in ascending order (min-priority queue):
- Initial Queue: 1,3,4,8,14,22
- Operation: poll() removes the highest priority element (smallest value).
Result: 3,4,8,14,22 - Operation: add(2) inserts a new element.
Result: 2,3,4,8,14,22
Characteristics of a Priority Queue
Unlike a standard queue, where elements are processed in the order they arrive, a priority queue ensures that high-priority items are handled first. Here are its core characteristics:
- Priority Assignment:
Each element in the priority queue is associated with a priority value that determines its position. Higher-priority elements are placed ahead of lower-priority ones. - Priority-Based Deletion:
Elements are dequeued based on their priority. The highest-priority item is always removed first, regardless of when it was added to the queue. - FIFO for Identical Priorities:
When two or more elements have the same priority, they are dequeued in the order they were inserted, following the first-in, first-out (FIFO) rule.
Why Priority Queues Stand Out?
- Efficient Task Management: Handles tasks by urgency or importance, making it ideal for scheduling, navigation, and algorithmic operations.
- Dynamic Organization: Continuously reorganizes elements to ensure the highest priority items are always accessible.
- Fair Processing: Maintains fairness by adhering to FIFO rules for elements with equal priority.
Example in Action
In a hospital’s emergency room, a patient with a critical condition would be treated first (highest priority). If two patients have similar conditions, the one who arrived is attended to first.
Priority queues are essential in scenarios requiring efficient and organized task processing, ensuring that the most critical items are addressed without delays.
What are the Different Types of Priority Queues?
A priority queue organizes elements based on their assigned priority, and the type of priority queue determines how these priorities are interpreted. There are two primary types of priority queues: ascending order priority queues and descending order priority queues. These structures differ in how they assign priority and process elements. Let’s explore them in detail.
1. Ascending Order Priority Queue
In an ascending order priority queue in data structure, elements with lower values are considered higher priority. This means that when dequeuing, the smallest value is removed first. The priority is inversely proportional to the numerical value of the elements.
Example:
Consider a priority queue with elements: 2, 4, 6, 8, 10.
- The queue arranges the elements in ascending order: 2, 4, 6, 8, 10.
- 2 has the highest priority, so it will be dequeued first.
- Subsequent operations continue to remove elements in ascending order of their values.
Applications:
- Commonly used in pathfinding algorithms, such as Dijkstra’s algorithm, where smaller distances or costs must be processed first.
- Suitable for priority-based scheduling where tasks with lower numerical identifiers or lower resource requirements need to be handled first.
Implementation Notes:
- Often implemented using min-heaps, as they allow efficient retrieval and deletion of the smallest value.
- A binary heap is typically used, providing logarithmic time complexity (O(logn)) for both insertion and deletion operations.
2. Descending Order Priority Queue
In a descending order priority queue, elements with higher values are given precedence. This means that the largest value is dequeued first. The priority is directly proportional to the numerical value of the elements.
Example:
Consider a priority queue with elements: 1, 2, 3, 4, 5, 9.
- The queue arranges the elements in descending order: 9, 4, 5, 3, 2, 1.
- 45 has the highest priority, so it will be dequeued first.
- Subsequent operations remove elements in descending order of their values.
Applications:
- Frequently used in event-driven systems or real-time task scheduling, where higher-priority tasks (e.g., tasks with greater urgency or importance) must be handled first.
- Useful in Prim’s algorithm for constructing a minimum spanning tree, where edges with higher weights are prioritized.
Implementation Notes:
- Typically implemented using max-heaps, which efficiently provide the largest value.
- A max-heap, structured as a binary tree, ensures logarithmic time complexity (O(logn)) for insertions and deletions.
Key Differences Between Ascending and Descending Priority Queues
Feature |
Ascending Order Priority Queue |
Descending Order Priority Queue |
Priority Rule |
Lower value = Higher priority |
Higher value = Higher priority |
First Element Dequeued |
Smallest value |
Largest value |
Common Implementation |
Min-heap |
Max-heap |
Primary Use Case |
Pathfinding, cost-efficient operations |
Task scheduling, urgent tasks management |
Implementation of Priority Queue in Data Structure
Priority queues can be implemented using various data structures. Each method offers distinct advantages and trade-offs, depending on the use case.
1. Linked List Implementation
A linked list can implement a priority queue by maintaining elements in an order based on their priority. New elements are inserted at the correct position to preserve the order.
How It Works:
- New elements are inserted into the list at the correct position to maintain priority order.
- The head of the list always contains the element with the highest priority, making deletion O(1).
- Traversing the list during insertion ensures correct placement, with complexity O(n).
Problem Statement:
Implement a priority queue in data structure using a linked list where elements are inserted based on their priority, and the highest-priority element can be dequeued efficiently.
Code Implementation (C++):
cpp
#include <bits/stdc++.h>
using namespace std;
// Node structure for the priority queue
struct Node {
int data;
int priority;
Node* next;
};
// Function to create a new node
Node* newNode(int d, int p) {
Node* temp = new Node();
temp->data = d;
temp->priority = p;
temp->next = nullptr;
return temp;
}
// Function to remove the element with the highest priority
void pop(Node** head) {
Node* temp = *head;
*head = (*head)->next;
delete temp;
}
// Function to add an element into the priority queue
void push(Node** head, int d, int p) {
Node* temp = newNode(d, p);
// If the queue is empty or new node has higher priority than the head
if (*head == nullptr || (*head)->priority < p) {
temp->next = *head;
*head = temp;
} else {
Node* start = *head;
while (start->next != nullptr && start->next->priority >= p) {
start = start->next;
}
temp->next = start->next;
start->next = temp;
}
}
// Function to get the element with the highest priority
int peek(Node* head) {
return head->data;
}
// Driver code
int main() {
Node* pq = nullptr;
push(&pq, 10, 2);
push(&pq, 20, 4);
push(&pq, 30, 3);
push(&pq, 40, 1);
while (pq != nullptr) {
cout << "Top element: " << peek(pq) << endl;
pop(&pq);
}
return 0;
}
Output:
Explanation of Output:
- The elements are dequeued in the order of their priority (highest first).
- 20 is dequeued first as it has the highest priority (4).
- The next elements 30, 10, and 40 are dequeued in descending order of priority.
Complexity:
- Insertion: O(n) (due to scanning for correct position).
- Deletion: O(1) (removing the head).
Use Cases:
- Suitable for applications requiring flexible insertion and retrieval.
- Not ideal for large datasets due to O(n) insertion time.
2. Binary Heap Implementation
A binary heap is the most efficient way to implement a priority queue. It uses a complete binary tree structure, ensuring logarithmic time for insertion and deletion operations.
How It Works:
- Use a max heap to always keep the element with the highest priority at the root.
- Insertions are done by placing the new element at the end of the heap and adjusting its position using the heapify-up operation.
- Deletion involves removing the root, replacing it with the last element, and performing a heapify-down operation to maintain the heap property.
Problem Statement:
Implement a priority queue in data structure using a binary heap, allowing efficient insertion and removal of the highest-priority element.
Code Implementation (C++):
cpp
#include <bits/stdc++.h>
using namespace std;
// Class for a max-heap-based priority queue
class PriorityQueue {
vector<int> heap;
// Heapify-down to maintain the heap property after deletion
void heapifyDown(int idx) {
int largest = idx;
int left = 2 * idx + 1;
int right = 2 * idx + 2;
if (left < heap.size() && heap[left] > heap[largest]) largest = left;
if (right < heap.size() && heap[right] > heap[largest]) largest = right;
if (largest != idx) {
swap(heap[idx], heap[largest]);
heapifyDown(largest);
}
}
// Heapify-up to maintain the heap property after insertion
void heapifyUp(int idx) {
if (idx == 0) return;
int parent = (idx - 1) / 2;
if (heap[idx] > heap[parent]) {
swap(heap[idx], heap[parent]);
heapifyUp(parent);
}
}
public:
// Insert a new element
void push(int val) {
heap.push_back(val);
heapifyUp(heap.size() - 1);
}
// Remove the element with the highest priority
void pop() {
if (heap.empty()) return;
heap[0] = heap.back();
heap.pop_back();
heapifyDown(0);
}
// Get the element with the highest priority
int peek() {
return heap.empty() ? -1 : heap[0];
}
// Check if the queue is empty
bool isEmpty() {
return heap.empty();
}
};
// Driver code
int main() {
PriorityQueue pq;
pq.push(10);
pq.push(50);
pq.push(30);
pq.push(20);
while (!pq.isEmpty()) {
cout << "Top element: " << pq.peek() << endl;
pq.pop();
}
return 0;
}
Output:
Explanation of Output:
- The elements are dequeued in descending order of priority, as the max heap maintains the largest element at the root.
- 50 is dequeued first, followed by 30, 20, and 10.
- The heap ensures efficient insertion (O(logn)) and removal (O(logn)).
Complexity:
- Insertion: O(logn).
- Deletion: O(logn).
- Peek: O(1).
Use Cases:
- Ideal for applications like Dijkstra’s algorithm, Prim’s algorithm, and event scheduling.
- Efficient for handling large datasets with dynamic updates.
3. Array-Based Implementation
Priority queues can also be implemented using arrays, either ordered or unordered.
How It Works:
- In an unordered array, elements are appended at the end, and the highest-priority element is found during deletion.
- In an ordered array, elements are inserted in sorted order to allow O(1) deletion of the highest-priority element.
Problem Statement:
Implement a priority queue using an array, where elements are stored with their priority values, and the highest-priority element is retrieved efficiently.
Code Implementation (C++):
cpp
#include <bits/stdc++.h>
using namespace std;
// Priority queue using unordered array
class PriorityQueue {
vector<pair<int, int>> arr;
public:
// Add an element with priority
void push(int val, int priority) {
arr.push_back({priority, val});
}
// Remove the element with the highest priority
void pop() {
auto it = max_element(arr.begin(), arr.end());
arr.erase(it);
}
// Get the element with the highest priority
int peek() {
auto it = max_element(arr.begin(), arr.end());
return it->second;
}
// Check if the queue is empty
bool isEmpty() {
return arr.empty();
}
};
// Driver code
int main() {
PriorityQueue pq;
pq.push(10, 2);
pq.push(20, 5);
pq.push(15, 3);
while (!pq.isEmpty()) {
cout << "Top element: " << pq.peek() << endl;
pq.pop();
}
return 0;
}
Output:
Explanation of Output:
- The highest-priority element is retrieved and removed in each operation.
- The array stores priorities, allowing manual comparison during retrieval.
Complexity:
- Unordered Array:
- Insertion: O(1).
- Deletion: O(n).
- Ordered Array:
- Insertion: O(n).
- Deletion: O(1).
Use Cases:
- Suitable for small datasets due to simplicity.
- Inefficient for large or frequently updated datasets.
4. Binary Search Tree (BST) Implementation
A binary search tree (e.g., AVL or Red-Black Tree) can implement a priority queue by maintaining priority ordering in its structure.
How It Works:
- Each node in the BST stores a priority value.
- Insertion and deletion maintain the BST’s order, ensuring efficient retrieval of the highest/lowest priority.
Complexity:
- Insertion: O(logn).
- Deletion: O(logn).
- Peek: O(1) (if root holds the highest priority).
Use Cases:
- Suitable for applications requiring efficient search and ordered priority retrieval.
- Trades-off simplicity for more memory overhead due to pointers.
Comparison of Implementations
Operation |
Unordered Array |
Ordered Array |
Binary Heap |
BST |
Insert |
O(1) |
O(n) |
O(logn) |
O(logn) |
Peek |
O(n) |
O(1) |
O(1) |
O(1) |
Delete |
O(n) |
O(1) |
O(logn) |
O(logn) |
Applications of Priority Queue
Priority queues are widely used in various systems and algorithms where prioritizing tasks or data is essential. Here are some common applications explained with practical examples to show their importance.
1. CPU Scheduling
Operating systems use priority queues to manage and schedule tasks based on their priority level.
Example:
In a computer system, processes are given priority levels. For instance:
- Task A: Priority 3 (High)
- Task B: Priority 2 (Medium)
- Task C: Priority 1 (Low)
The CPU executes Task A first, followed by Task B and Task C. This ensures urgent tasks, such as system updates, are completed before less critical ones. Priority queues make this scheduling efficient and organized.
2. Graph Algorithms
Dijkstra’s Shortest Path Algorithm:
In this algorithm, a min-priority queue in data structure stores nodes based on their current shortest distance from the source. The node with the smallest distance is processed first.
Example:
In a navigation system, such as Google Maps, the shortest route is calculated using Dijkstra’s algorithm. A priority queue helps prioritize the next closest node to evaluate, ensuring the most efficient path is found.
Prim’s Minimum Spanning Tree Algorithm:
This algorithm uses a min-priority queue to select edges with the smallest weights to construct a minimum spanning tree.
Example:
In a network design, such as laying fiber-optic cables, Prim’s algorithm helps minimize costs by selecting the shortest connections between points.
3. Data Compression
Priority queues are used in Huffman coding, a popular method for reducing file sizes.
How It Works:
Huffman coding assigns shorter binary codes to frequently occurring characters and longer codes to less frequent ones. A min-priority queue combines the characters with the lowest frequencies first.
Example:
If a text contains the following character frequencies:
- A: 5, B: 3, C: 2, D: 1.
The priority queue helps build a binary tree where characters with the smallest frequencies (C and D) are combined first. This tree generates efficient encodings, reducing the overall size of the compressed file.
4. Simulation
Priority queues are used in simulations to handle events based on their priority, ensuring critical tasks are processed before others.
Example:
In a hospital’s emergency room, patients are assigned priorities based on the severity of their condition:
- Patient X: Critical condition (Priority 3)
- Patient Y: Minor injury (Priority 1)
- Patient Z: Serious injury (Priority 2)
A priority queue ensures Patient X is attended to first, followed by Patient Z and Patient Y.
Other Simulation Scenarios:
- In banks, VIP customers are served first.
- In gaming, critical game events are processed before less important ones.
5. Networking
Routers use priority queues to manage data packets. Critical packets, like live video streams or emergency signals, are prioritized over less important packets like file downloads.
Example:
If a router processes the following packets:
- Live stream data: Priority 3
- Email: Priority 1
- Web browsing: Priority 2
The priority queue ensures live stream data is transmitted first, maintaining smooth performance for time-sensitive tasks.
6. Search Algorithms
A Search Algorithm:*
Priority queues are used in A* search to explore paths based on their cost and estimated distance to the target.
Example:
In robotic navigation, the algorithm uses a priority queue to evaluate the most promising paths first, reducing time and computation required to reach the destination.
Why Study Priority Queues in Data Structures?
Priority queues are a game-changer in data structures, powering solutions in navigation, scheduling, and more. Learning them sharpens your problem-solving skills and helps you tackle advanced algorithms like Dijkstra’s shortest path and Huffman coding.
Why Are Priority Queues Essential?
- Boost Your Algorithm Game: Master the logic behind real-world systems like route optimization and data compression.
- Career Edge: Knowledge of priority queues is a sought-after skill in roles like software developer, system architect, and data engineer.
- Solve Real Problems: From task management in operating systems to simulations, priority queues make systems smarter and more efficient.
Learn Priority Queues with upGrad
Ready to strengthen your skills? upGrad’s expert-led courses in data structures and algorithms are the perfect way to grow.
Why Choose upGrad?
- Work on real-world projects.
- Get certifications recognized by top employers.
- Learn from industry professionals.
Your next career move starts here! Explore upGrad Courses Now!
Elevate your expertise with our range of Popular Data Science Courses. Browse the programs below to discover your ideal fit.
Explore our Popular Data Science Courses
Advance your in-demand data science skills with our top programs. Discover the right course for you below.
Top Data Science Skills to Learn
Explore popular articles related to data science to enhance your knowledge. Browse the programs below to find your ideal match.
Read our popular Data Science Articles
Frequently Asked Questions (FAQs)
1. What is the difference between a normal queue and a priority queue?
A normal queue processes elements in the order they are added, following the first-in, first-out (FIFO) rule. A priority queue processes elements based on their priority, where higher-priority elements are dequeued before lower-priority ones, regardless of when they were added.
2. Which data structures are best for implementing priority queues?
Binary heaps (min-heaps or max-heaps) are the most efficient choice for implementing priority queues because they allow quick insertions and deletions (O(logn)). Other options include linked lists, arrays, and binary search trees, depending on the size of the dataset and specific requirements.
3. Can a priority queue have elements with the same priority?
Yes, elements in a priority queue can share the same priority. In such cases, they are typically dequeued in the order they were added, following the first-in, first-out (FIFO) rule for elements with equal priority.
4. How does a priority queue work in Dijkstra’s algorithm?
In Dijkstra’s algorithm, a min-priority queue stores nodes based on their shortest distance from the starting point. Nodes with the smallest distance are processed first, which helps efficiently find the shortest path to all other nodes in the graph.
5. What is the time complexity of a binary heap implementation of a priority queue?
For a binary heap implementation:
- Insertion: O(logn).
- Deletion (removing the highest-priority element): O(logn).
- Peek (accessing the highest-priority element): O(1).
6. Why would you use a priority queue instead of a standard queue?
A priority queue is used when the order of processing is more important than the order of arrival. It is ideal for tasks like scheduling processes in an operating system or finding the shortest path in graph algorithms, where urgency or importance determines the order of execution.
7. What are the different types of priority queues?
Priority queues can be of two types:
- Ascending Order Priority Queue: Elements with the smallest value have the highest priority and are dequeued first.
- Descending Order Priority Queue: Elements with the largest value have the highest priority and are dequeued first.
8. Can you implement a priority queue using an array?
Yes, a priority queue can be implemented using an array. In an unordered array, new elements are added at the end, and the highest or lowest priority is found during deletion (O(n)). In an ordered array, elements are inserted in sorted order (O(n)O(n)O(n)), allowing for O(1) deletion of the highest-priority element.
9. How do max heaps and min heaps work in priority queues?
- In a max heap, the root node contains the largest element, representing the highest priority. When the root is removed, the heap is restructured to maintain this property.
- In a min heap, the root node contains the smallest element, representing the highest priority. The heap reorganizes itself to keep this property intact after an element is removed.
10. In what situations are priority queues commonly used?
Priority queues are often used in:
- CPU scheduling: To handle tasks based on urgency.
- Graph algorithms: Such as Dijkstra’s shortest path and Prim’s minimum spanning tree.
- Data compression: Like Huffman coding.
- Simulations: To process events in the order of their importance.
- Networking: To ensure critical data packets are transmitted first.
11. How does the priority queue handle insertions and deletions differently than other data structures?
In a priority queue, elements are inserted in a way that maintains their order based on priority, not on when they were added. Deletions always target the highest-priority element, unlike standard queues that process elements based on the first-in, first-out or last-in, first-out rules.