Priority Queue in Data Structure: Characteristics, Types & Implementation

# Priority Queue in Data Structure: Characteristics, Types & Implementation

Last updated:
15th Jul, 2024
Views
15 Mins
View All

## 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:

• 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

 Executive Post Graduate Programme in Data Science from IIITB Professional Certificate Program in Data Science for Business Decision Making Master of Science in Data Science from University of Arizona Advanced Certificate Programme in Data Science from IIITB Professional Certificate Program in Data Science and Business Analytics from University of Maryland Data Science Courses

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.

1. 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.
2. 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

1. You can perform the following steps to delete an element in the Priority Queue in Data Structure.
2. 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.
3. 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.
4. 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.
5. 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

 Top Data Science Skills to Learn 1 Data Analysis Course Inferential Statistics Courses 2 Hypothesis Testing Programs Logistic Regression Courses 3 Linear Regression Courses Linear Algebra for Analysis

### 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   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

 Data Science Career Path: A Comprehensive Career Guide Data Science Career Growth: The Future of Work is here Why is Data Science Important? 8 Ways Data Science Brings Value to the Business Relevance of Data Science for Managers The Ultimate Data Science Cheat Sheet Every Data Scientists Should Have Top 6 Reasons Why You Should Become a Data Scientist A Day in the Life of Data Scientist: What do they do? Myth Busted: Data Science doesn’t need Coding Business Intelligence vs Data Science: What are the differences?

## 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.

#### Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.
Get Free Consultation

Select
Select Area of interest
Select Work Experience
By clicking 'Submit' you Agree to

#### Data Science Skills to Master

1What 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.

2What 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.

3What 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.

4What 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).

5How 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.

6What 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.

7What 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.

## Suggested Blogs

142460
Association Rule Mining in data mining, as the name suggests, involves discovering relationships between seemingly independent relational databases or

13 Jul 2024

101801
Why data mining techniques are important like never before? Businesses these days are collecting data at a very striking rate. The sources of this eno

12 Jul 2024

58170
Pandas is a BSD-licensed and open-source Python library offering high-performance, easy-to-use data structures, and data analysis tools. The full form

11 Jul 2024

99398
Data types are an essential concept in the python programming language. In Python, every value has its own python data type. The classification of dat

11 Jul 2024

16859
Introduction to Data Mining In its raw form, data requires efficient processing to transform into valuable information. Predicting outcomes hinges on

04 Jul 2024

82932
What is a Data Analytics Lifecycle? Data is crucial in today’s digital world. As it gets created, consumed, tested, processed, and reused, data goes

04 Jul 2024

10560
Introduction Data structures are one of the most fundamental concepts in object-oriented programming. To explain it simply, a data structure is a par

03 Jul 2024

70323
Summary: In this article, you will learn, Difference between Data Science and Data Analytics Job roles Skills Career perspectives Which one is right