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. This blog will give you a deeper understanding of the priority queue and its implementation in the C programming language.
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 queue is termed as a priority queue if it has the following characteristics:
- Each item has some priority associated with it.
- An item with the highest priority is moved at the front and deleted first.
- If two elements share the same priority value, then the priority queue follows the first-in-first-out principle for de queue operation.
What are the Types of Priority Queue?
A priority queue is of two types:
- Ascending Order Priority Queue
- Descending Order Priority Queue
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
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
Binary Heap
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.
- equal to or more than the value of a child node.
The above process divides the binary heap into two types: max heap and min-heap.
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.
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.
- Shift the data at the end of the tree by swapping it with the last node data.
- Remove the last element of the binary 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.
Top Data Science Skills to Learn in 2022
SL. No
Top Data Science Skills to Learn in 2022
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 <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.
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
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.
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:
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:
The following illustrates the difference between max heap and min-heap.What are the applications of a 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. What approach is used in the implementation of the priority queue using array?
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. What is 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.