Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconData Sciencebreadcumb forward arrow iconPriority Queue in Data Structure: Characteristics, Types & Implementation

Priority Queue in Data Structure: Characteristics, Types & Implementation

Last updated:
2nd May, 2021
Views
Read Time
9 Mins
share image icon
In this article
Chevron in toc
View All
Priority Queue in Data Structure: Characteristics, Types & Implementation

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.

4812203545

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.

4535201284

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.

OperationUnordered ArrayOrdered ArrayBinary HeapBinary Search Tree
Insert0(1)0(N)0(log(N))0(log(N))
Peek0(N)0(1)0(1)0(1)
Delete0(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.

  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.
  3. Shift the data at the end of the tree by swapping it with the last node data.
  4. Remove the last element of the binary 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.

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.

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.

Profile

Rohit Sharma

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

Frequently Asked Questions (FAQs)

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.

Explore Free Courses

Suggested Blogs

Python Free Online Course with Certification [2023]
115921
Summary: In this Article, you will learn about python free online course with certification. Programming with Python: Introduction for Beginners Lea
Read More

by Rohit Sharma

20 Sep 2023

Information Retrieval System Explained: Types, Comparison &amp; Components
47654
An information retrieval (IR) system is a set of algorithms that facilitate the relevance of displayed documents to searched queries. In simple words,
Read More

by Rohit Sharma

19 Sep 2023

26 Must Read Shell Scripting Interview Questions &#038; Answers [For Freshers &#038; Experienced]
12972
For those of you who use any of the major operating systems regularly, you will be interacting with one of the two most critical components of an oper
Read More

by Rohit Sharma

17 Sep 2023

4 Types of Data: Nominal, Ordinal, Discrete, Continuous
284097
Summary: In this Article, you will learn about 4 Types of Data Qualitative Data Type Nominal Ordinal Quantitative Data Type Discrete Continuous R
Read More

by Rohit Sharma

14 Sep 2023

Data Science Course Eligibility Criteria: Syllabus, Skills &#038; Subjects
42436
Summary: In this article, you will learn in detail about Course Eligibility Demand Who is Eligible? Curriculum Subjects & Skills The Science Beh
Read More

by Rohit Sharma

14 Sep 2023

Data Scientist Salary in India in 2023 [For Freshers &#038; Experienced]
900793
Summary: In this article, you will learn about Data Scientist salaries in India based on Location, Skills, Experience, country and more. Read the com
Read More

by Rohit Sharma

12 Sep 2023

16 Data Mining Projects Ideas &#038; Topics For Beginners [2023]
48884
Introduction A career in Data Science necessitates hands-on experience, and what better way to obtain it than by working on real-world data mining pr
Read More

by Rohit Sharma

12 Sep 2023

Actuary Salary in India in 2023 &#8211; Skill and Experience Required
899290
Do you have a passion for numbers? Are you interested in a career in mathematics and statistics? If your answer was yes to these questions, then becom
Read More

by Rohan Vats

12 Sep 2023

Most Frequently Asked NumPy Interview Questions and Answers [For Freshers]
24469
If you are looking to have a glorious career in the technological sphere, you already know that a qualification in NumPy is one of the most sought-aft
Read More

by Rohit Sharma

12 Sep 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon