×

Priority Queue in Data Structure

Priority Queue

A priority queue is a special kind of queue, in priority queue we give some priority to an element and according to this priority an element can be served in the queue.

Generally, the value of element is treated as the priority of an element. Like, the element has highest value treated as the highest priority element as well as we assume that if element has lowest value treated as the highest priority element in the other case, we can give the priorities to elements according to our requirements.

Difference between in normal queue and a Priority Queue

If we talk about the normal queue works on first in first out rule whereas, in a priority queue element is removed according to the priority, an element with the highest priority is removed first.

Types of Priority Queue

There are two types of priority queue :

a Max-Priority Queue and a Min- Priority Queue. In these types, the priority queue stores the collections of elements and it is only able to provide the most “Extreme” element.

Implementation of Priority Queue

There are many ways to implement priority queue like, array, linked list, binary heap etc. If we talk about heap data structure then it provides an efficient way of implementing priority queues.

Complexity of Priority Queue : -

OperationsInsertPeekDelete
Linked ListO(1)O(n)O(1)
Binary HeapO(1)O(log n)O(log n)

Operations on Priority Queue

The operations of priority queues are inserting element, removing element, getting element. We are using Binary heap data structure for implementing of priority queue.

1. Add an new element into Priority Queue :

Here we are using max heap data structure for priority queue

  • Add new element at the end of tree.
Priority Queue in Data Structure
  • Heapify the tree
Priority Queue in Data Structure

2. Removing an element from the Priority Queue : -

  • Select the element which you want to delete
Priority Queue in Data Structure
  • Swap that element with last element
Priority Queue in Data Structure
  • Remove the last element and heapify the tree
Priority Queue in Data Structure

3. Getting an element from the Priority Queue :

Return the root node without deleting the element of tree

Priority Queue Implementation in C language

#include <stdio.h>
 int len = 0;
 void swap(int *a, int *b)
 {
                 int temp = *b;
                 *b = *a;
                 *a = temp;
 }
 void heapify_Tree(int queue[] , int len , int i) // For Re-Balance the tree
 {
 if (len == 1)
 {
 printf("the heap has only one element");
                                                             }
 else
 {
        int largest_ele= i;
        int l = 2 * i + 1;
        int r = 2 * i + 2;
          if (l < len && queue[l] > queue[largest_ele])
         largest_ele = l;
                       if (r < len && queue[r] > queue[largest_ele])
                        largest_ele = r;
         if (largest_ele != i)
 {
                  swap(&queue[i] , &queue[largest_ele]);
                           heapify_Tree(queue , len , largest_ele);
                                                                          }
                                                                 }
 }
 void insert(int queue[] , int newNum) // For adding new element in to tree
 {
           if (len == 0)
  {
               queue[0] = newNum;
              len += 1;
              }
 else
  {
            queue[len] = newNum;
               len += 1;
 for (int i = len / 2-1 ; i >= 0 ; i--)
 {
       heapify_Tree(queue , len , i);
  }
      }
 }
 void deleteElement(int queue[] , int num) // For removing desired element from the tree
 {
   int i;
   for (i = 0 ; i < len ; i++)
 {
    if (num == queue[i])
     break ;
    }
 swap(&queue[i] , &queue[len - 1]);
      len -= 1;
   for (int i = len / 2-1 ; i >= 0 ; i--)
 {
     heapify_Tree(queue , len , i);
                                                             }
 }
 void delete(int queue[]) // For extracting max element (root node) from the tree
 {
             swap(&queue[0],&queue[len-1]);
             printf("Removed highest priority element : %d\n" , queue[len-1]);
             len -= 1;
     for (int i = len-1  ; i >= 0 ; i--)
 {
             heapify_Tree(queue , len , i);
                                                             }                      
 }
 void printQueue(int queue[] , int len) // For printing the elements
 {
 for (int i = 0 ; i < len ; ++i)
   printf("%d " , queue[i]);
   printf("\n");
 }
 int main() // Driver code
 {
   int queue[10];
   insert(queue , 3);
   insert(queue , 4);
 insert(queue , 9);
 insert(queue , 5);
 insert(queue , 2);
 insert(queue , 1);
 insert(queue , 0);
  printf("Max-Heap queue : ");
  printQueue(queue , len);
  deleteElement(queue , 4);
  printf("After deleting an element : ");
  printQueue(queue , len);
  delete(queue);
  printf("After deleting the highest priority element : ");
  printQueue(queue , len);
 } 

Output :

Priority Queue in Data Structure

Applications of Priority Queue

  • In Hauffman Coding
  • For Implementing Stack
  • In Dijkstra’s Algorithm
  • In Prim’s Minimum Spanning Tree
  • Process Scheduling in OS
  • All Queue Applications where Priority Involved

Related Topics

Linear vs Non-Linear: Data Structure

What is Linear Data Structure? The data structure is said to be linear if the data elements are arranged linearly or we can say sequentially. In the linear data structure, the...

3 minutes read.

Deletion Operation of the binary search tree in C++ language

A typical binary search tree implements some order to carry out the arrangements. As the name suggests, each parent node should have at most two children. The main rule in...

4 minutes read.

Create a binary search tree

Implementation In this section of the article, we will see the usage and mechanism of how we will create a given binary tree. Let's observe these in more depth and then...

7 minutes read.

Hashing and its Applications

Hashing Hashing refers to transforming plain text data in such a way that even if it is leaked for some reason, no one would be able to make sense of it....

6 minutes read.

Given a Binary Tree Check the Zig-Zag Traversal

Implementation // The C++ implementation of the zig-zag traversal method in the O(n) time.  #include <iostream> #include <stack> using namespace std; // creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a...

4 minutes read.

Properties of Binary Tree

Trees are maybe of the most significant datum structures. They are used to store and figure out data. A binarytree is a tree data structure made from nodes, all of which has...

3 minutes read.

Optimal binary search tree in DSA

Implementation // A simple way of the recursive implementation of the optimal search that we will perform on the binary tree.   #include <bits/stdc++.h> using namespace std; // we have to create a basic utility...

8 minutes read.

Depth of binary tree

We all know that a binary tree is a kind of tree that helps us maintain the order and balance of the tree. It is a type of tree in...

4 minutes read.

Application of 2D array - Sparse Matrix

2D Arrays Application - Sparse Matrix A matrix is a two-dimensional data item consisting of m rows and n columns, with a total of m x n values. A sparse matrix...

7 minutes read.

Find Number of Minimum Insertion to Make a String Palindrome

You have been given a string. You have to find out the number of minimum insertions to make this string palindrome. The string will contain only lower case alphabets. Note:What is...

4 minutes read.

Permutation Sort or Bogo Sort

In Permutation Sort or Bogo Sort, you have been given one array, which consists of different values. You have to sort the array using BOGO sort. Let’s take an example: Input-...

3 minutes read.

Stack vs Heap Memory Allocation Data Structure

Difference Between Stack and Heap Memory Allocation Stack Memory Stack memory allocation is a way to use the system memory as a temporary storage of the data which is act like last-in-first-out...

3 minutes read.

Trim a binary search tree

Implementation //writing a C++ program will help us eliminate the keys that are out of the league.  #include<bits/stdc++.h> using namespace std; //we are now creating a binary search tree node consisting of key left...

8 minutes read.

Binary Tree vs Binary Search Tree: Data Structure

Difference Between Binary Tree and Binary Search Tree What is Binary Tree? A tree which each node can have utmost two children called binary tree. These children are referred as the ‘left...

3 minutes read.

Lowest common ancestor in a binary search tree

Suppose you have given two values of nodes in a binary search tree. You have to find out the lowest common ancestor between the nodes. Let’s take an example tree- For the...

4 minutes read.

Comb Sort

Brush sort is a fairly direct orchestrating computation at first arranged by Wlodzimierz Dobosiewicz and Artur Borowy in 1980, later rediscovered (and given the name "Combsort") by Stephen Lacey and...

5 minutes read.

Extended Binary Tree

A form of binary tree known as an extended binary tree replaces all of the original tree's null subtrees with special nodes known as external nodes, while the remaining nodes...

4 minutes read.

A Full Binary Tree with n Nodes

Implementation // Writing the implementation of the above approach in C++ #include <bits/stdc++.h> using namespace std; // We are creating a class that will create a node and its left and right children.  struct __nod...

12 minutes read.

Merge Sort

Merge Sort is one of the most widely used sorting algorithms, and it is based on the Divide and Conquer principle. A problem is subdivided into multiple sub-problems in this method....

8 minutes read.

Find Bridges in a Graph

You have been given a graph. You have to find out the bridges in that graph. Graph may be connected or disconnected. You have to print vertices of particular edge...

4 minutes read.