- 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 16 July, 2024
58.57K+ views
• 15 min read
Table of Contents
Introduction
The priority queue in the data structure is an extension of the “normal” queue. It is an abstract data type that contains a group of items. It is like the “normal” queue except that the dequeuing elements follow a priority order. The priority order dequeues those items first that have the highest priority.
Each priority queue in DS comes with its own importance and is essential for handling various task priorities with ease. Their adaptability is key to solving many computer science problems effectively. They are widely used in software development for effectively managing various elements.
They play a vital role in operating systems by prioritizing important tasks, which helps improve system performance. Networks also rely on them to handle data packets, ensuring timely delivery of essential information. Algorithms like Dijkstra’s shortest path algorithm use priority queues to find the most efficient paths.
Additionally, they assist in processing events in simulations based on their importance. They serve as a versatile tool in computer science, aiding in handling various tasks and problems across different applications.
This blog will give you a deeper understanding of the priority queue and its implementation in the C programming language. Read on to learn everything from priority queue example in data structure to the deletion algorithm for priority queue.
What is a Priority Queue?
It is an abstract data type that provides a way to maintain the dataset. The “normal” queue follows a pattern of first-in-first-out. It dequeues elements in the same order followed at the time of insertion operation. However, the element order in a priority queue depends on the element’s priority in that queue. The priority queue moves the highest priority elements at the beginning of the priority queue and the lowest priority elements at the back of the priority queue.
It supports only those elements that are comparable. Hence, a priority queue in the data structure arranges the elements in either ascending or descending order.
You can think of a priority queue as several patients waiting in line at a hospital. Here, the situation of the patient defines the priority order. The patient with the most severe injury would be the first in the queue.
What are the Characteristics of a Priority Queue?
A priority queue in data structure is a variant of a traditional queue that stands out due to its priority-based organization. Unlike a standard queue, it distinguishes elements by assigning priority values that change how they’re accessed.
The design of a priority queue in DS optimizes the management and processing of elements based on their priorities. Its applications span various fields, including scheduling tasks, handling network data, and algorithmic design, where prioritization is crucial for efficient operations and problem-solving.
A queue is termed as a priority queue if it has the following characteristics:
- Each item has some priority associated with it.
Each item in a priority queue is tagged with a priority value, signifying its importance or urgency. This helps distinguish between elements based on specific criteria, like prioritizing critical tasks over those of less urgent ones.
- An item with the highest priority is moved at the front and deleted first.
Unlike standard queues, a priority queue places the highest-priority item at the front. This ensures immediate access and processing of crucial elements and alters the order in which items are handled based on their priority.
- If two elements share the same priority value, then the priority queue follows the first-in-first-out principle for de queue operation.
When multiple items share the same priority, a priority queue follows the ‘first-in-first-out’ principle. This means items with identical priorities are processed in the order they were added, ensuring fairness in their treatment.
What are the Types of Priority Queue?
A priority queue is of two types:
- Ascending Order Priority Queue
An ascending priority queue arranges elements based on their priority values in ascending order. This means the element with the smallest priority value sits at the front for dequeuing. When inserting new elements, they’re placed according to their priority, maintaining the order.
For dequeuing, the element with the smallest priority (considered the highest priority) is removed first. This example of priority queue is appropriate when handling elements with the lowest priority is a top priority, ensuring that less urgent tasks or data are processed foremost.
- Descending Order Priority Queue
A descending order priority queue arranges elements by their priority values in descending order. The item with the highest priority value takes precedence for dequeuing. New elements are added accordingly, maintaining this order.
During dequeuing, the highest-priority element, holding the utmost significance, is retrieved first. It suits scenarios where handling the most crucial or urgent elements is paramount, ensuring they’re processed promptly.
This queue is beneficial when prioritizing tasks, events, or data with the highest urgency. Implementations can employ various structures like sorted arrays or linked lists to maintain this descending priority order efficiently.
Also read: Free data structures and algorithm course!
Ascending Order Priority Queue
An ascending order priority queue gives the highest priority to the lower number in that queue. For example, you have six numbers in the priority queue that are 4, 8, 12, 45, 35, 20. Firstly, you will arrange these numbers in ascending order. The new list is as follows: 4, 8, 12, 20. 35, 45. In this list, 4 is the smallest number. Hence, the ascending order priority queue treats number 4 as the highest priority.
4 | 8 | 12 | 20 | 35 | 45 |
In the above table, 4 has the highest priority, and 45 has the lowest priority.
Must read: Learn excel online free!
Descending Order Priority Queue
A descending order priority queue gives the highest priority to the highest number in that queue. For example, you have six numbers in the priority queue that are 4, 8, 12, 45, 35, 20. Firstly, you will arrange these numbers in ascending order. The new list is as follows: 45, 35, 20, 12, 8, 4. In this list, 45 is the highest number. Hence, the descending order priority queue treats number 45 as the highest priority.
45 | 35 | 20 | 12 | 8 | 4 |
In the above table, 4 has the lowest priority, and 45 has the highest priority.
Our learners also read: Free Python Course with Certification
Implementation of the Priority Queue in Data Structure
There are several types of priority queue in data structure, and each come with a separate use case for separate scenarios.
You can implement the priority queues in one of the following ways:
- Linked list
- Binary heap
- Arrays
- Binary search tree
The binary heap is the most efficient method for implementing the priority queue in the data structure.
The below tables summarize the complexity of different operations in a priority queue.
Operation | Unordered Array | Ordered Array | Binary Heap | Binary Search Tree |
Insert | 0(1) | 0(N) | 0(log(N)) | 0(log(N)) |
Peek | 0(N) | 0(1) | 0(1) | 0(1) |
Delete | 0(N) | 0(1) | 0(log (N)) | 0(log(N)) |
Explore our Popular Data Science Courses
Linked List
A linked list used as a priority queue operates by arranging elements according to their priorities. When an element is added, it finds its place in the list based on its priority level, aligning either from the lowest to the highest or vice versa.
Accessing elements involves scanning through the list to find the one with the highest or lowest priority. Deleting elements follows their priority order, removing them in line with their importance. Linked lists allow for flexible operations such as adding, removing, and locating high or low-priority elements.
However, due to its structure, pinpointing specific elements might take longer than other data structures. Deciding to use a linked list as a priority queue depends on balancing its flexibility with the potential trade-offs in terms of access speed for certain tasks or systems.
Binary Heap
A tree-based data structure with a specific arrangement that satisfies the heap property is known as a binary heap. When employed as a priority queue, it provides efficient access to the highest (in a max heap) or lowest (in a min heap) priority element.
A binary heap priority queue offers an efficient way to manage priorities by organizing elements in a hierarchical tree structure. It provides quick access to the highest or lowest priority element, making it valuable in scenarios where prioritization and efficient retrieval of extreme values are essential, such as in scheduling, graph algorithms, and sorting.
A binary heap tree organises all the parent and child nodes of the tree in a particular order. In a binary heap tree, a parent node can have a maximum of 2 child nodes. The value of the parent node could either be:
- equal to or less than the value of a child node.This ensures that the largest element (the maximum value) is at the root node. It guarantees that each parent node holds a value lesser than or equal to its child nodes. It preserves the hierarchical structure where every level maintains this property. As a result, the maximum value is always present at the root of the heap.
- equal to or more than the value of a child node.The value of the parent node is equal to or more than the values of its child nodes. This ensures that the smallest element (the minimum value) is at the root node. It guarantees that each parent node holds a value greater than or equal to its child nodes, maintaining the hierarchical arrangement where every level follows this rule. Consequently, the minimum value is always at the root of the heap.
The above process divides the binary heap into two types: max heap and min-heap.
Array
Arrays provide a solid foundation for building a priority queue in data structures. They organize elements based on their priorities, often in order from lowest to highest or vice versa.
Each element’s position in the array corresponds to its priority level, allowing quick access to high or low-priority items. Adding elements involves placing them in the array according to their priority and possibly readjusting to maintain the order.
Deleting elements often targets the highest or lowest priority element, usually found at the start or end of the array. Arrays offer fast access to elements using their index. However, their fixed size might need adjustment as the queue changes, affecting performance and memory use. While arrays efficiently handle priority-based access, their size limitations and potential resizing issues need consideration when adapting to varying system needs.
Max Heap
The max heap is a binary heap in which a parent node has a value either equal to or greater than the child node value. The root node of the tree has the highest value.
This design ensures that the biggest value, the top priority, sits at the root. Inserting elements means placing them in the right spot to maintain this order.
Deleting involves replacing the root with the last element and adjusting to maintain the structure. Max heaps are useful in priority queues for quick access to the highest priority and in sorting algorithms like heap sort. Their primary strength lies in quickly accessing the maximum value, making them valuable for tasks prioritizing the largest elements.
Watch our Webinar on Transformation & Opportunities in Analytics & Insights
Inserting an Element in a Max Heap Binary Tree
You can perform the following steps to insert an element/number in the priority queue in the data structure.
- The algorithm scans the tree from top to bottom and left to right to find an empty slot. It then inserts the element at the last node in the tree.
- After inserting the element, the order of the binary tree is disturbed. You must swap the data with each other to sort the order of the max heap binary tree. You must keep shuffling the data until the tree satisfies the max-heap property.
Algorithm to Insert an Element in a Max Heap Binary Tree
If the tree is empty and contains no node,
create a new parent node newElement.
else (a parent node is already available)
insert the newElement at the end of the tree (i.e., last node of the tree from left to right.)
max-heapify the tree
Deleting an Element in a Max Heap Binary Tree
- You can perform the following steps to delete an element in the Priority Queue in Data Structure.
- Choose the element that you want to delete from the binary tree.Start the deletion process by singling out the element you intend to remove from the binary tree. Typically, this focuses on the element with the highest priority, especially in a max heap scenario.
- Shift the data at the end of the tree by swapping it with the last node data.To efficiently maintain the structure of the binary tree, replace your element of choice with the data from the last node in the tree. This process involves swapping the data of the element to be deleted with the data from the last node. This action ensures that the tree remains complete.
- Remove the last element of the binary tree.Once the data has been swapped, the last node of the binary tree, which now contains the element to be deleted, is removed. This action effectively eliminates the duplicate or now-relocated element from the tree.
- After deleting the element, the order of the binary tree is disturbed. You must sort the order to satisfy the property of max-heap. You must keep shuffling the data until the tree meets the max-heap property.This process involves recursively shifting the element downwards in the tree until it finds the appropriate position according to the max-heap property.
Top Data Science Skills to Learn
Algorithm to Delete an Element in a Max Heap Binary Tree
If the elementUpForDeletion is the lastNode,
delete the elementUpForDeletion
else replace elementUpForDeletion with the lastNode
delete the elementUpForDeletion
max-heapify the tree
Find the Maximum or Minimum Element in a Max Heap Binary Tree
In a max heap binary tree, the find operation returns the parent node (the highest element) of the tree.
Algorithm to Find the Max or Min in a Max Heap Binary Tree
return ParentNode
Program Implementation of the Priority Queue using the Max Heap Binary Tree
#include <stdio.h>
int binary_tree = 10;
int max_heap = 0;
const int test = 100000;
void swap( int *x, int *y ) {
int a;
a = *x;
*x= *y;
*y = a;
}
//Code to find the parent in the max heap tree
int findParentNode(int node[], int root) {
if ((root > 1) && (root < binary_tree)) {
return root/2;
}
return -1;
}
void max_heapify(int node[], int root) {
int leftNodeRoot = findLeftChild(node, root);
int rightNodeRoot = findRightChild(node, root);
// finding highest among root, left child and right child
int highest = root;
if ((leftNodeRoot <= max_heap) && (leftNodeRoot >0)) {
if (node[leftNodeRoot] > node[highest]) {
highest = leftNodeRoot;
}
}
if ((rightNodeRoot <= max_heap) && (rightNodeRoot >0)) {
if (node[rightNodeRoot] > node[highest]) {
highest = rightNodeRoot;
}
}
if (highest != root) {
swap(&node[root], &node[highest]);
max_heapify(node, highest);
}
}
void create_max_heap(int node[]) {
int d;
for(d=max_heap/2; d>=1; d–) {
max_heapify(node, d);
}
}
int maximum(int node[]) {
return node[1];
}
int find_max(int node[]) {
int maxNode = node[1];
node[1] = node[max_heap];
max_heap–;
max_heapify(node, 1);
return maxNode;
}
void descend_key(int node[], int node, int key) {
A[root] = key;
max_heapify(node, root);
}
void increase_key(int node[], int root, int key) {
node[root] = key;
while((root>1) && (node[findParentNode(node, root)] < node[root])) {
swap(&node[root], &node[findParentNode(node, root)]);
root = findParentNode(node, root);
}
}
void insert(int node[], int key) {
max_heap++;
node[max_heap] = -1*test;
increase_key(node, max_heap, key);
}
void display_heap(int node[]) {
int d;
for(d=1; d<=max_heap; d++) {
printf(“%d\n”,node[d]);
}
printf(“\n”);
}
int main() {
int node[binary_tree];
insert(node, 10);
insert(node, 4);
insert(node, 20);
insert(node, 50);
insert(node, 1);
insert(node, 15);
display_heap(node);
printf(“%d\n\n”, maximum(node));
display_heap(node);
printf(“%d\n”, extract_max(node));
printf(“%d\n”, extract_max(node));
return 0;
}
Min Heap
The min-heap is a binary heap in which a parent node has a value equal to or lesser than the child node value. The root node of the tree has the lowest value.
It’s often represented using arrays and maintains a complete binary tree structure for efficient storage. New elements are added by appending and adjusting their position to maintain the min-heap property.
To delete the minimum element (root), it’s replaced with the last element while preserving the heap’s structure. Min heaps are handy in priority queues for fast access to the lowest priority. They’re used in Prim’s algorithm and heap sort due to their efficiency in handling smaller values.
You can implement the min-heap in the same manner as the max-heap except reverse the order.
Read our popular Data Science Articles
Conclusion
A priority queue in DS serves as a crucial tool, managing elements based on their priorities. Whether applied in algorithms, simulations, or organizing events, the priority queue ensures the timely processing of high-priority elements.
Using efficient structures such as binary heaps or arrays, it optimizes computational processes across different scenarios, enhancing system efficiency and responsiveness. This foundational concept significantly contributes to smoother task management and streamlined operations in numerous applications within the digital landscape.
The examples given in the article are only for explanatory purposes. You can modify the statements given above as per your requirements. In this blog, we learned about the concept of the priority queue in the data structure. You can try out the example to strengthen your data structure knowledge.
If you are curious to learn about data science, check out IIIT-B & upGrad’s Executive PG Programme in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.
Learn data science courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
Frequently Asked Questions (FAQs)
1. What are the applications of a priority queue?
The priority queue is a special queue where the elements are inserted on the basis of their priority. This feature comes to be useful in the implementation of various other data structures. The following are some of the most popular applications of the priority queue:
1. Dijkstra’s Shortest Path algorithm: Priority queue can be used in Dijkstra’s Shortest Path algorithm when the graph is stored in the form of the adjacency list.
2. Prim’s Algorithm: Prim’s algorithm uses the priority queue to the values or keys of nodes and draws out the minimum of these values at every step.
Data Compression: Huffman codes use the priority queue to compress the data.
Operating Systems: The priority queue is highly useful for operating systems in various processes such as load balancing and interruption handling.
2. What approach is used in the implementation of the priority queue using array?
The approach used in the implementation of the priority queue using an array is simple. A structure is created to store the values and priority of the element and then the array of that structure is created to store the elements. The following operations are involved in this implementation:
1. enqueue()-This function inserts the elements at the end of the queue.
2. peek() - This function will traverse the array to return the element with the highest priority. If it finds two elements having the same priority, it returns the highest value element among them.
3. dequeue() - This function will shift all the elements, 1 position to the left of the element returned by the peek() function and decrease the size.
3. What is the difference between max heap and min heap?
The following illustrates the difference between max heap and min-heap.
Min Heap - In a min-heap, the key of the root node must be less than or equal to the keys of its children node. It uses ascending priority. The node with the smallest key is the priority. The smallest element is popped before any other element.
Max Heap - In a max heap, the key of the root node must be greater than or equal to the key of its children’s nodes. It uses descending priority. The node with the largest key is the priority. The largest element is popped before any other element.
4. What is the rule of priority queue?
A priority queue serves elements based on their priority, with higher priority elements dequeued first. If elements have the same priority, they are served in the order they were added (FIFO).
5. How can I implement a priority queue in C using an array?
To implement a priority queue using an array in C, you can maintain an array of structures where each structure holds the data and its priority. Insertion involves adding the element at the correct position based on its priority while deletion involves removing the element with the highest priority.
6. What is a priority queue in Python?
A priority queue in Python is a data structure where each element is associated with a priority. Elements with higher priorities are dequeued before elements with lower priorities. Python's module provides an implementation of the priority queue.
7. What are the common use cases of priority queues in C++?
Priority queues in C++ are commonly used in scenarios like implementing Dijkstra's algorithm for shortest paths, A* algorithm for pathfinding, job scheduling systems and any application that requires dynamic ordering of elements based on priority.
Did you find this article helpful?
Our Trending Courses
MS in Data Science Post Graduate Programme in Data Science & AI (Executive) DBA in Emerging Technologies with concentration in Generative AIOur Trending Skill
Data Analysis Inferential Statistics Logistic Regression Linear Regression Linear Algebra for Analysis Hypothesis TestingGet Free Consultation
By clicking "Submit" you Agree toupGrad's Terms & Conditions
FREE COURSES
Start Learning For Free