The Wayback Machine - https://web.archive.org/web/20240828040545/https://www.geeksforgeeks.org/priority-queue-set-1-introduction/
Open In App

What is Priority Queue | Introduction to Priority Queue

Last Updated : 05 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A priority queue is a type of queue that arranges elements based on their priority values. Elements with higher priority values are typically retrieved or removed before elements with lower priority values. Each element has a priority value associated with it. When we add an item, it is inserted in a position based on its priority value.

There are several ways to implement a priority queue, including using an array, linked list, heap, or binary search tree, binary heap being the most common method to implement. The reason for using Binary Heap is simple, in binary heaps, we have easy access to the min (in min heap) or max (in max heap) and binary heap being a complete binary tree are easily implemented using arrays. Since we use arrays, we have cache friendliness advantage also.

Priority queues are often used in real-time systems, where the order in which elements are processed is not simply based on the fact who came first (or inserted first), but based on priority. Priority Queue is used in algorithms such as Dijkstra’s algorithm, Prim’s algorithm, Kruskal’s algorithm and Huffnam Coding.

Properties of Priority Queue

So, a priority Queue is an extension of the queue with the following properties. 

  • Every item has a priority associated with it.
  • An element with high priority is dequeued before an element with low priority.
  • If two elements have the same priority, they are served according to their order in the queue.

In the below priority queue, an element with a maximum ASCII value will have the highest priority. The elements with higher priority are served first. 

How is Priority assigned to the elements in a Priority Queue?

In a priority queue, generally, the value of an element is considered for assigning the priority. 

For example, the element with the highest value is assigned the highest priority and the element with the lowest value is assigned the lowest priority. The reverse case can also be used i.e., the element with the lowest value can be assigned the highest priority. Also, the priority can be assigned according to our needs. 

Operations of a Priority Queue:

A typical priority queue supports the following operations:

1) Insertion in a Priority Queue

When a new element is inserted in a priority queue, it moves to the empty slot from top to bottom and left to right. However, if the element is not in the correct place then it will be compared with the parent node. If the element is not in the correct order, the elements are swapped. The swapping process continues until all the elements are placed in the correct position.

2) Deletion in a Priority Queue  

As you know that in a max heap, the maximum element is the root node. And it will remove the element which has maximum priority first. Thus, you remove the root node from the queue. This removal creates an empty slot, which will be further filled with new insertion. Then, it compares the newly inserted element with all the elements inside the queue to maintain the heap invariant.

3) Peek in a Priority Queue

This operation helps to return the maximum element from Max Heap or the minimum element from Min Heap without deleting the node from the priority queue.

Types of Priority Queue:

1) Ascending Order Priority Queue

As the name suggests, in ascending order priority queue, the element with a lower priority value is given a higher priority in the priority list. For example, if we have the following elements in a priority queue arranged in ascending order like 4,6,8,9,10. Here, 4 is the smallest number, therefore, it will get the highest priority in a priority queue and so when we dequeue from this type of priority queue, 4 will remove from the queue and dequeue returns 4.

2) Descending order Priority Queue 

The root node is the maximum element in a max heap, as you may know. It will also remove the element with the highest priority first. As a result, the root node is removed from the queue. This deletion leaves an empty space, which will be filled with fresh insertions in the future. The heap invariant is then maintained by comparing the newly inserted element to all other entries in the queue.

Types of Priority Queues

Types of Priority Queues

Difference between Priority Queue and Normal Queue?

There is no priority attached to elements in a queue, the rule of first-in-first-out(FIFO) is implemented whereas, in a priority queue, the elements have a priority. The elements with higher priority are served first.

How to Implement Priority Queue? 

Priority queue can be implemented using the following data structures: 

  • Arrays
  • Linked list
  • Heap data structure
  • Binary search tree

Let’s discuss all these in detail.

1) Implement Priority Queue Using Array: 

A simple implementation is to use an array of the following structure. 

struct item {
        int item;
        int priority;
}

  • enqueue(): This function is used to insert new data into the queue.
  • dequeue(): This function removes the element with the highest priority from the queue.
  • peek()/top(): This function is used to get the highest priority element in the queue without removing it from the queue.

Arrays

enqueue()

dequeue()

peek()

Time Complexity

O(1)

O(n)

O(n)

C++
// C++ program to implement Priority Queue
// using Arrays
#include <bits/stdc++.h>
using namespace std;

// Structure for the elements in the
// priority queue
struct item {
    int value;
    int priority;
};

// Store the element of a priority queue
item pr[100000];

// Pointer to the last index
int size = -1;

// Function to insert a new element
// into priority queue
void enqueue(int value, int priority)
{
    // Increase the size
    size++;

    // Insert the element
    pr[size].value = value;
    pr[size].priority = priority;
}

// Function to check the top element
int peek()
{
    int highestPriority = INT_MIN;
    int ind = -1;

    // Check for the element with
    // highest priority
    for (int i = 0; i <= size; i++) {

        // If priority is same choose
        // the element with the
        // highest value
        if (highestPriority == pr[i].priority && ind > -1
            && pr[ind].value < pr[i].value) {
            highestPriority = pr[i].priority;
            ind = i;
        }
        else if (highestPriority < pr[i].priority) {
            highestPriority = pr[i].priority;
            ind = i;
        }
    }

    // Return position of the element
    return ind;
}

// Function to remove the element with
// the highest priority
void dequeue()
{
    // Find the position of the element
    // with highest priority
    int ind = peek();

    // Shift the element one index before
    // from the position of the element
    // with highest priority is found
    for (int i = ind; i < size; i++) {
        pr[i] = pr[i + 1];
    }

    // Decrease the size of the
    // priority queue by one
    size--;
}

// Driver Code
int main()
{
    // Function Call to insert elements
    // as per the priority
    enqueue(10, 2);
    enqueue(14, 4);
    enqueue(16, 4);
    enqueue(12, 3);

    // Stores the top element
    // at the moment
    int ind = peek();

    cout << pr[ind].value << endl;

    // Dequeue the top element
    dequeue();

    // Check the top element
    ind = peek();
    cout << pr[ind].value << endl;

    // Dequeue the top element
    dequeue();

    // Check the top element
    ind = peek();
    cout << pr[ind].value << endl;

    return 0;
}
Java
// Java program to implement Priority Queue
// using Arrays
import java.util.*;

// Structure for the elements in the
// priority queue
class item {
  public int value;
  public int priority;
};

class GFG {

  // Store the element of a priority queue
  static item[] pr = new item[100000];

  // Pointer to the last index
  static int size = -1;
  // Function to insert a new element
  // into priority queue
  static void enqueue(int value, int priority)
  {
    // Increase the size
    size++;

    // Insert the element
    pr[size] = new item();
    pr[size].value = value;
    pr[size].priority = priority;
  }

  // Function to check the top element
  static int peek()
  {
    int highestPriority = Integer.MIN_VALUE;
    int ind = -1;

    // Check for the element with
    // highest priority
    for (int i = 0; i <= size; i++) {

      // If priority is same choose
      // the element with the
      // highest value
      if (highestPriority == pr[i].priority
          && ind > -1
          && pr[ind].value < pr[i].value) {
        highestPriority = pr[i].priority;
        ind = i;
      }
      else if (highestPriority < pr[i].priority) {
        highestPriority = pr[i].priority;
        ind = i;
      }
    }

    // Return position of the element
    return ind;
  }

  // Function to remove the element with
  // the highest priority
  static void dequeue()
  {
    // Find the position of the element
    // with highest priority
    int ind = peek();

    // Shift the element one index before
    // from the position of the element
    // with highest priority is found
    for (int i = ind; i < size; i++) {
      pr[i] = pr[i + 1];
    }

    // Decrease the size of the
    // priority queue by one
    size--;
  }

  public static void main(String[] args)
  {
    // Function Call to insert elements
    // as per the priority
    enqueue(10, 2);
    enqueue(14, 4);
    enqueue(16, 4);
    enqueue(12, 3);

    // Stores the top element
    // at the moment
    int ind = peek();

    System.out.println(pr[ind].value);

    // Dequeue the top element
    dequeue();

    // Check the top element
    ind = peek();
    System.out.println(pr[ind].value);

    // Dequeue the top element
    dequeue();

    // Check the top element
    ind = peek();
    System.out.println(pr[ind].value);
  }
}

// this code is contributed by phasing17
Python
import sys

# Structure for the elements in the
# priority queue
class item :
    value = 0
    priority = 0
class GFG :
  
    # Store the element of a priority queue
    pr = [None] * (100000)
    
    # Pointer to the last index
    size = -1
    
    # Function to insert a new element
    # into priority queue
    @staticmethod
    def enqueue( value,  priority) :
      
        # Increase the size
        GFG.size += 1
        
        # Insert the element
        GFG.pr[GFG.size] = item()
        GFG.pr[GFG.size].value = value
        GFG.pr[GFG.size].priority = priority
        
    # Function to check the top element
    @staticmethod
    def  peek() :
        highestPriority = -sys.maxsize
        ind = -1
        
        # Check for the element with
        # highest priority
        i = 0
        while (i <= GFG.size) :
          
            # If priority is same choose
            # the element with the
            # highest value
            if (highestPriority == GFG.pr[i].priority and ind > -1 and GFG.pr[ind].value < GFG.pr[i].value) :
                highestPriority = GFG.pr[i].priority
                ind = i
            elif(highestPriority < GFG.pr[i].priority) :
                highestPriority = GFG.pr[i].priority
                ind = i
            i += 1
            
        # Return position of the element
        return ind
      
    # Function to remove the element with
    # the highest priority
    @staticmethod
    def dequeue() :
      
        # Find the position of the element
        # with highest priority
        ind = GFG.peek()
        
        # Shift the element one index before
        # from the position of the element
        # with highest priority is found
        i = ind
        while (i < GFG.size) :
            GFG.pr[i] = GFG.pr[i + 1]
            i += 1
            
        # Decrease the size of the
        # priority queue by one
        GFG.size -= 1
    @staticmethod
    def main( args) :
      
        # Function Call to insert elements
        # as per the priority
        GFG.enqueue(10, 2)
        GFG.enqueue(14, 4)
        GFG.enqueue(16, 4)
        GFG.enqueue(12, 3)
        
        # Stores the top element
        # at the moment
        ind = GFG.peek()
        print(GFG.pr[ind].value)
        
        # Dequeue the top element
        GFG.dequeue()
        
        # Check the top element
        ind = GFG.peek()
        print(GFG.pr[ind].value)
        
        # Dequeue the top element
        GFG.dequeue()
        
        # Check the top element
        ind = GFG.peek()
        print(GFG.pr[ind].value)
    
if __name__=="__main__":
    GFG.main([])
    
    # This code is contributed by aadityaburujwale.
C#
// C# program to implement Priority Queue
// using Arrays

using System;

// Structure for the elements in the
// priority queue
public class item {
    public int value;
    public int priority;
};


public class GFG
{
    
    // Store the element of a priority queue
    static item[] pr = new item[100000];

    // Pointer to the last index
    static int size = -1;
    // Function to insert a new element
    // into priority queue
    static void enqueue(int value, int priority)
    {
        // Increase the size
        size++;
    
        // Insert the element
        pr[size] = new item();
        pr[size].value = value;
        pr[size].priority = priority;
    }
    
    // Function to check the top element
    static int peek()
    {
        int highestPriority =  int.MinValue;
        int ind = -1;
    
        // Check for the element with
        // highest priority
        for (int i = 0; i <= size; i++) {
    
            // If priority is same choose
            // the element with the
            // highest value
            if (highestPriority == pr[i].priority && ind > -1
                && pr[ind].value < pr[i].value) {
                highestPriority = pr[i].priority;
                ind = i;
            }
            else if (highestPriority < pr[i].priority) {
                highestPriority = pr[i].priority;
                ind = i;
            }
        }
    
        // Return position of the element
        return ind;
    }
    
    // Function to remove the element with
    // the highest priority
    static void dequeue()
    {
        // Find the position of the element
        // with highest priority
        int ind = peek();
    
        // Shift the element one index before
        // from the position of the element
        // with highest priority is found
        for (int i = ind; i < size; i++) {
            pr[i] = pr[i + 1];
        }
    
        // Decrease the size of the
        // priority queue by one
        size--;
    }

    public static void Main(string[] args)
    {
         // Function Call to insert elements
        // as per the priority
        enqueue(10, 2);
        enqueue(14, 4);
        enqueue(16, 4);
        enqueue(12, 3);
    
        // Stores the top element
        // at the moment
        int ind = peek();
    
        Console.WriteLine(pr[ind].value);
    
        // Dequeue the top element
        dequeue();
    
        // Check the top element
        ind = peek();
        Console.WriteLine(pr[ind].value);
    
        // Dequeue the top element
        dequeue();
    
        // Check the top element
        ind = peek();
        Console.WriteLine(pr[ind].value);
    }
}

//this code is contributed by phasing17
JavaScript
// JavaScript program to implement Priority Queue
// using Arrays

// Structure for the elements in the
// priority queue
class item {
    constructor()
    {
        this.value;
        this.priority;
    }
};

// Store the element of a priority queue
let pr = [];
for (var i = 0; i < 100000; i++)
    pr.push(new item());

// Pointer to the last index
let size = -1;

// Function to insert a new element
// into priority queue
function enqueue(value, priority)
{
    // Increase the size
    size++;

    // Insert the element
    pr[size] = new item();
    pr[size].value = value;
    pr[size].priority = priority;
}

// Function to check the top element
function peek()
{
    let highestPriority = Number.MIN_SAFE_INTEGER;
    let ind = -1;

    // Check for the element with
    // highest priority
    for (var i = 0; i <= size; i++) {

        // If priority is same choose
        // the element with the
        // highest value
        if (highestPriority == pr[i].priority && ind > -1
            && pr[ind].value < pr[i].value) {
            highestPriority = pr[i].priority;
            ind = i;
        }
        else if (highestPriority < pr[i].priority) {
            highestPriority = pr[i].priority;
            ind = i;
        }
    }

    // Return position of the element
    return ind;
}

// Function to remove the element with
// the highest priority
function dequeue()
{
    // Find the position of the element
    // with highest priority
    let ind = peek();

    // Shift the element one index before
    // from the position of the element
    // with highest priority is found
    for (var i = ind; i < size; i++) {
        pr[i] = pr[i + 1];
    }

    // Decrease the size of the
    // priority queue by one
    size--;
}

// Function Call to insert elements
// as per the priority
enqueue(10, 2);
enqueue(14, 4);
enqueue(16, 4);
enqueue(12, 3);

// Stores the top element
// at the moment
let ind = peek();

console.log(pr[ind].value);

// Dequeue the top element
dequeue();

// Check the top element
ind = peek();
console.log(pr[ind].value);

// Dequeue the top element
dequeue();

// Check the top element
ind = peek();
console.log(pr[ind].value);

// this code is contributed by phasing17

Output
16
14
12

Note: Read this article for more details.

2) Implement Priority Queue Using Linked List: 

In a LinkedList implementation, the entries are sorted in descending order based on their priority. The highest priority element is always added to the front of the priority queue, which is formed using linked lists. The functions like push(), pop(), and peek() are used to implement a priority queue using a linked list and are explained as follows:

  • push(): This function is used to insert new data into the queue.
  • pop(): This function removes the element with the highest priority from the queue.
  • peek() / top(): This function is used to get the highest priority element in the queue without removing it from the queue.

Linked List

push()

pop()

peek()

Time Complexity

 O(n)   

 O(1)  

O(1)

C++
// C++ code to implement Priority Queue
// using Linked List
#include <bits/stdc++.h>
using namespace std;

// Node
typedef struct node {
    int data;

    // Lower values indicate
    // higher priority
    int priority;

    struct node* next;

} Node;

// Function to create a new node
Node* newNode(int d, int p)
{
    Node* temp = (Node*)malloc(sizeof(Node));
    temp->data = d;
    temp->priority = p;
    temp->next = NULL;

    return temp;
}

// Return the value at head
int peek(Node** head) { return (*head)->data; }

// Removes the element with the
// highest priority form the list
void pop(Node** head)
{
    Node* temp = *head;
    (*head) = (*head)->next;
    free(temp);
}

// Function to push according to priority
void push(Node** head, int d, int p)
{
    Node* start = (*head);

    // Create new Node
    Node* temp = newNode(d, p);

    // Special Case: The head of list has
    // lesser priority than new node
    if ((*head)->priority < p) {

        // Insert New Node before head
        temp->next = *head;
        (*head) = temp;
    }
    else {

        // Traverse the list and find a
        // position to insert new node
        while (start->next != NULL
               && start->next->priority > p) {
            start = start->next;
        }

        // Either at the ends of the list
        // or at required position
        temp->next = start->next;
        start->next = temp;
    }
}

// Function to check is list is empty
int isEmpty(Node** head) { return (*head) == NULL; }

// Driver code
int main()
{

    // Create a Priority Queue
    // 7->4->5->6
    Node* pq = newNode(4, 1);
    push(&pq, 5, 2);
    push(&pq, 6, 3);
    push(&pq, 7, 0);

    while (!isEmpty(&pq)) {
        cout << " " << peek(&pq);
        pop(&pq);
    }
    return 0;
}
Java
// Java code to implement Priority Queue
// using Linked List
import java.util.* ;

class Solution
{

// Node
static class Node {
    int data;
    
    // Lower values indicate higher priority
    int priority;
    Node next;
    
}

static Node node = new Node();
    
// Function to Create A New Node
static Node newNode(int d, int p)
{
    Node temp = new Node();
    temp.data = d;
    temp.priority = p;
    temp.next = null;
    
    return temp;
}
    
// Return the value at head
static int peek(Node head)
{
    return (head).data;
}
    
// Removes the element with the
// highest priority from the list
static Node pop(Node head)
{
    Node temp = head;
    (head) = (head).next;
    return head;
}
    
// Function to push according to priority
static Node push(Node head, int d, int p)
{
    Node start = (head);
    
    // Create new Node
    Node temp = newNode(d, p);
    
    // Special Case: The head of list has lesser
    // priority than new node. So insert new
    // node before head node and change head node.
    if ((head).priority < p) {
    
        // Insert New Node before head
        temp.next = head;
        (head) = temp;
    }
    else {
    
        // Traverse the list and find a
        // position to insert new node
        while (start.next != null &&
            start.next.priority > p) {
            start = start.next;
        }
    
        // Either at the ends of the list
        // or at required position
        temp.next = start.next;
        start.next = temp;
    }
    return head;
}
    
// Function to check is list is empty
static int isEmpty(Node head)
{
    return ((head) == null)?1:0;
}
    
// Driver code
public static void main(String args[])
{
    // Create a Priority Queue
    // 7.4.5.6
    Node pq = newNode(4, 1);
    pq =push(pq, 5, 2);
    pq =push(pq, 6, 3);
    pq =push(pq, 7, 0);
    
    while (isEmpty(pq)==0) {
        System.out.printf("%d ", peek(pq));
        pq=pop(pq);
    }
    
}
}

// This code is contributed by ishankhandelwals.
Python
# Python3 code to implement Priority Queue
# using Singly Linked List

# Class to create new node which includes
# Node Data, and Node Priority
class PriorityQueueNode:

    def _init_(self, value, pr):

        self.data = value
        self.priority = pr
        self.next = None

# Implementation of Priority Queue


class PriorityQueue:

    def _init_(self):

        self.front = None

    # Method to check Priority Queue is Empty
    # or not if Empty then it will return True
    # Otherwise False
    def isEmpty(self):

        return True if self.front == None else False

    # Method to add items in Priority Queue
    # According to their priority value
    def push(self, value, priority):

        # Condition check for checking Priority
        # Queue is empty or not
        if self.isEmpty() == True:

            # Creating a new node and assigning
            # it to class variable
            self.front = PriorityQueueNode(value,
                                           priority)

            # Returning 1 for successful execution
            return 1

        else:

            # Special condition check to see that
            # first node priority value
            if self.front.priority < priority:

                # Creating a new node
                newNode = PriorityQueueNode(value,
                                            priority)

                # Updating the new node next value
                newNode.next = self.front

                # Assigning it to self.front
                self.front = newNode

                # Returning 1 for successful execution
                return 1

            else:

                # Traversing through Queue until it
                # finds the next smaller priority node
                temp = self.front

                while temp.next:

                    # If same priority node found then current
                    # node will come after previous node
                    if priority >= temp.next.priority:
                        break

                    temp = temp.next

                newNode = PriorityQueueNode(value,
                                            priority)
                newNode.next = temp.next
                temp.next = newNode

                # Returning 1 for successful execution
                return 1

    # Method to remove high priority item
    # from the Priority Queue
    def pop(self):

        # Condition check for checking
        # Priority Queue is empty or not
        if self.isEmpty() == True:
            return

        else:

            # Removing high priority node from
            # Priority Queue, and updating front
            # with next node
            self.front = self.front.next
            return 1

    # Method to return high priority node
    # value Not removing it
    def peek(self):

        # Condition check for checking Priority
        # Queue is empty or not
        if self.isEmpty() == True:
            return
        else:
            return self.front.data

    # Method to Traverse through Priority
    # Queue
    def traverse(self):

        # Condition check for checking Priority
        # Queue is empty or not
        if self.isEmpty() == True:
            return "Queue is Empty!"
        else:
            temp = self.front
            while temp:
                print(temp.data, end=" ")
                temp = temp.next


# Driver code
if _name_ == "_main_":

    # Creating an instance of Priority
    # Queue, and adding values
    # 7 -> 4 -> 5 -> 6
    pq = PriorityQueue()
    pq.push(4, 1)
    pq.push(5, 2)
    pq.push(6, 3)
    pq.push(7, 0)

    # Traversing through Priority Queue
    pq.traverse()

    # Removing highest Priority item
    # for priority queue
    pq.pop()
C#
// C# code to implement Priority Queue 
// using Linked List 
using System; 

class GFG 
{ 
  // Node 
  public class Node 
  { 
    public int data; 

    // Lower values indicate 
    // higher priority 
    public int priority; 

    public Node next; 
  } 

  public static Node node = new Node(); 

  // Function to Create A New Node 
  public static Node newNode(int d, int p) 
  { 
    Node temp = new Node(); 
    temp.data = d; 
    temp.priority = p; 
    temp.next = null; 

    return temp; 
  } 

  // Return the value at head 
  public static int peek(Node head) 
  { 
    return (head).data; 
  } 

  // Removes the element with the 
  // highest priority from the list 
  public static Node pop(Node head) 
  { 
    Node temp = head; 
    (head) = (head).next; 
    return head; 
  } 

  // Function to push according to priority 
  public static Node push(Node head, 
                          int d, int p) 
  { 
    Node start = (head); 

    // Create new Node 
    Node temp = newNode(d, p); 

    // Special Case: The head of list 
    // has lesser priority than new node. 
    // So insert new node before head node 
    // and change head node. 
    if ((head).priority < p) 
    { 

      // Insert New Node before head 
      temp.next = head; 
      (head) = temp; 
    } 
    else
    { 

      // Traverse the list and find a 
      // position to insert new node 
      while (start.next != null && 
             start.next.priority > p) 
      { 
        start = start.next; 
      } 

      // Either at the ends of the list 
      // or at required position 
      temp.next = start.next; 
      start.next = temp; 
    } 
    return head; 
  } 

  // Function to check is list is empty 
  public static int isEmpty(Node head) 
  { 
    return ((head) == null) ? 1 : 0; 
  } 

  // Driver code 
  public static void Main(string[] args) 
  { 
    // Create a Priority Queue 
    // 7.4.5.6 
    Node pq = newNode(4, 1); 
    pq = push(pq, 5, 2); 
    pq = push(pq, 6, 3); 
    pq = push(pq, 7, 0); 

    while (isEmpty(pq) == 0) 
    { 
      Console.Write("{0:D} ", peek(pq)); 
      pq = pop(pq); 
    } 
  } 
}

// This code is contributed by ishankhandelwals.
JavaScript
// JavaScript code to implement Priority Queue
// using Linked List
// Node
class Node {

    // Lower values indicate
    // higher priority
    constructor() {
        this.data = 0;
        this.priority = 0;
        this.next = null;
    }
}

var node = new Node();

// Function to Create A New Node
function newNode(d, p) {
    var temp = new Node();
    temp.data = d;
    temp.priority = p;
    temp.next = null;

    return temp;
}

// Return the value at head
function peek(head) {
    return head.data;
}

// Removes the element with the
// highest priority from the list
function pop(head) {
    var temp = head;
    head = head.next;
    return head;
}

// Function to push according to priority
function push(head, d, p) {
    var start = head;

    // Create new Node
    var temp = newNode(d, p);

    // Special Case: The head of list
    // has lesser priority than new node.
    // So insert new node before head node
    // and change head node.
    if (head.priority < p) {

        // Insert New Node before head
        temp.next = head;
        head = temp;
    }
    else {

        // Traverse the list and find a
        // position to insert new node
        while (start.next != null && start.next.priority > p) {
            start = start.next;
        }

        // Either at the ends of the list
        // or at required position
        temp.next = start.next;
        start.next = temp;
    }
    return head;
}

// Function to check is list is empty
function isEmpty(head) {
    return head == null ? 1 : 0;
}

// Driver code
// Create a Priority Queue
// 7.4.5.6
var pq = newNode(4, 1);
pq = push(pq, 5, 2);
pq = push(pq, 6, 3);
pq = push(pq, 7, 0);

while (isEmpty(pq) == 0) {
    console.log(peek(pq)," ");
    pq = pop(pq);
}

// This code is contributed by ishankhandelwals.

Output
 6 5 4 7

Refer to this article for more details.

Note: We can also use Linked List, time complexity of all operations with linked list remains same as array. The advantage with linked list is deleteHighestPriority() can be more efficient as we don’t have to move items. 

3) Implement Priority Queue Using Heaps: 

Binary Heap is generally preferred for priority queue implementation because heaps provide better performance compared to arrays or LinkedList. Considering the properties of a heap, The entry with the largest key is on the top and can be removed immediately. It will, however, take time O(log n) to restore the heap property for the remaining keys. However if another entry is to be inserted immediately, then some of this time may be combined with the O(log n) time needed to insert the new entry. Thus the representation of a priority queue as a heap proves advantageous for large n, since it is represented efficiently in contiguous storage and is guaranteed to require only logarithmic time for both insertions and deletions. Operations on Binary Heap are as follows: 

  • insert(p): Inserts a new element with priority p.
  • extractMax(): Extracts an element with maximum priority.
  • remove(i): Removes an element pointed by an iterator i.
  • getMax(): Returns an element with maximum priority.
  • changePriority(i, p): Changes the priority of an element pointed by i to p.

Binary Heap

insert()

remove()

peek()

Time Complexity

O(log n)

O(log n)

O(1)

Refer to this article for code implementation. 

4) Implement Priority Queue Using Binary Search Tree: 

A Self-Balancing Binary Search Tree like AVL Tree, Red-Black Tree, etc. can also be used to implement a priority queue. Operations like peek(), insert() and delete() can be performed using BST.

Binary Search Treepeek()insert()delete()
Time ComplexityO(1)O(log n)O(log n)

Applications of Priority Queue: 

Advantages of Priority Queue:

  • It helps to access the elements in a faster way. This is because elements in a priority queue are ordered by priority, one can easily retrieve the highest priority element without having to search through the entire queue.
  • The ordering of elements in a Priority Queue is done dynamically. Elements in a priority queue can have their priority values updated, which allows the queue to dynamically reorder itself as priorities change.
  • Efficient algorithms can be implemented. Priority queues are used in many algorithms to improve their efficiency, such as Dijkstra’s algorithm for finding the shortest path in a graph and the A* search algorithm for pathfinding.
  • Included in real-time systems. This is because priority queues allow you to quickly retrieve the highest priority element, they are often used in real-time systems where time is of the essence.

Disadvantages of Priority Queue:

  • High complexity. Priority queues are more complex than simple data structures like arrays and linked lists, and may be more difficult to implement and maintain.
  • High consumption of memory. Storing the priority value for each element in a priority queue can take up additional memory, which may be a concern in systems with limited resources.
  • It is not always the most efficient data structure. In some cases, other data structures like heaps or binary search trees may be more efficient for certain operations, such as finding the minimum or maximum element in the queue.
  • At times it is less predictable:. This is because the order of elements in a priority queue is determined by their priority values, the order in which elements are retrieved may be less predictable than with other data structures like stacks or queues, which follow a first-in, first-out (FIFO) or last-in, first-out (LIFO) order.

See also: 

  1. Applications of Priority Queue
  2. Priority Queue in C++
  3. Priority Queue in Java
  4. Priority Queue in Python
  5. Priority Queue in JavaScript
  6. Recent articles on Priority Queue!


Similar Reads

Should we declare as Queue or Priority Queue while using Priority Queue in Java?
Queue: Queue is an Interface that extends the collection Interface in Java and this interface belongs to java.util package. A queue is a type of data structure that follows the FIFO (first-in-first-out ) order. The queue contains ordered elements where insertion and deletion of elements are done at different ends. Priority Queue and Linked List are
3 min read
Priority Queue using Queue and Heapdict module in Python
Priority Queue is an extension of the queue with the following properties. An element with high priority is dequeued before an element with low priority. If two elements have the same priority, they are served according to their order in the queue. queue.PriorityQueue(maxsize) It is a constructor for a priority queue. maxsize is the number of eleme
3 min read
Why can't a Priority Queue wrap around like an ordinary Queue?
Priority Queue: A priority queue is a special type of queue in which each element is assigned a priority value. And elements are served based on their priority. This means that elements with higher priority are served first. However, if elements with the same priority occur, they will be served in the order in which they were queued. A priority que
3 min read
Can we use Simple Queue instead of Priority queue to implement Dijkstra's Algorithm?
What is Dijkstra's Algorithm? Dijkstra's Algorithm is used for finding the shortest path between any two vertices of a graph. It uses a priority queue for finding the shortest path. For more detail, about Dijkstra's Algorithm, you can refer to this article. Why Dijkstra's Algorithm uses a Priority Queue? We use min heap in Dijkstra's Algorithm beca
2 min read
Turn a Queue into a Priority Queue
What is Queue?Queue is an abstract data type that is open at both ends. One end is always used to insert data (enqueue) which is basically the rear/back/tail end and the other which is the front end is used to remove data (dequeue). Queue follows First-In-First-Out (FIFO) methodology, i.e., "the data item stored first will be accessed first". Decla
9 min read
Why does Queue have front but Priority-queue has top in stl?
Why does the queue have front but the priority queue has top in stl? The main difference between a queue and a priority queue is that a queue follows the FIFO (First-In-First-Out) principle, while a priority queue follows a specific priority order. In other words, the elements in a queue are processed in the order they were added, whereas the eleme
8 min read
Difference between Circular Queue and Priority Queue
Queues are fundamental data structures that are used to store and manage a collection of elements. While both circular queues and priority queues are types of queues, they have distinct characteristics and applications. This article will explore the key differences between circular queues and priority queues. Circular Queue:A Circular Queue is an e
4 min read
Priority Queue using Doubly Linked List
Given Nodes with their priority, implement a priority queue using doubly linked list. Prerequisite : Priority Queue push(): This function is used to insert a new data into the queue.pop(): This function removes the element with the lowest priority value from the queue.peek() / top(): This function is used to get the lowest priority element in the q
11 min read
Priority Queue in Python
Priority Queues are abstract data structures where each data/value in the queue has a certain priority. For example, In airlines, baggage with the title “Business” or “First-class” arrives earlier than the rest. Priority Queue is an extension of the queue with the following properties. An element with high priority is dequeued before an element wit
2 min read
Double ended priority queue
A double ended priority queue supports operations of both max heap (a max priority queue) and min heap (a min priority queue). The following operations are expected from double ended priority queue. getMax() : Returns maximum element.getMin() : Returns minimum element.deleteMax() : Deletes maximum element.deleteMin() : Deletes minimum element.size(
6 min read
Implementation of Non-Preemptive Shortest Job First using Priority Queue
Read here for Shortest Job First Scheduling algorithm for same arrival times.Shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting process with the smallest execution time to execute next.In this article, we will implement the Shortest Job First Scheduling algorithm (SJF) using a priority queue, so that we c
12 min read
Minimum Spanning Tree using Priority Queue and Array List
Given a bi-directed weighted (positive) graph without self-loops, the task is to generate the minimum spanning tree of the graph.Examples: Input: N = 9, E = 14, edges = {{0, 1, 4}, {0, 7, 8}, {1, 2, 8}, {1, 7, 11}, {2, 3, 7}, {2, 8, 2}, {2, 5, 4}, {3, 4, 9}, {3, 5, 14}, {4, 5, 10}, {5, 6, 2}, {6, 7, 1}, {6, 8, 6}, {7, 8, 7}} Output: ((A, B), Cost)
5 min read
Huffman Coding using Priority Queue
Prerequisite: Greedy Algorithms | Set 3 (Huffman Coding), priority_queue::push() and priority_queue::pop() in C++ STL Given a char array ch[] and frequency of each character as freq[]. The task is to find Huffman Codes for every character in ch[] using Priority Queue. Example Input: ch[] = { 'a', 'b', 'c', 'd', 'e', 'f' }, freq[] = { 5, 9, 12, 13,
12 min read
Find the K closest points to origin using Priority Queue
Given a list of n points on 2D plane, the task is to find the K (k &lt; n) closest points to the origin O(0, 0). Note: The distance between a point P(x, y) and O(0, 0) using the standard Euclidean Distance. Examples: Input: [(1, 0), (2, 1), (3, 6), (-5, 2), (1, -4)], K = 3 Output: [(1, 0), (2, 1), (1, -4)] Explanation: Square of Distances of points
7 min read
Heap and Priority Queue using heapq module in Python
Heaps are widely used tree-like data structures in which the parent nodes satisfy any one of the criteria given below. The value of the parent node in each level is less than or equal to its children's values - min-heap.The value of the parent node in each level higher than or equal to its children's values - max-heap. The heaps are complete binary
5 min read
Merge two sorted arrays using Priority queue
Given two sorted arrays A[] and B[] of sizes N and M respectively, the task is to merge them in a sorted manner. Examples: Input: A[] = { 5, 6, 8 }, B[] = { 4, 7, 8 }Output: 4 5 6 7 8 8 Input: A[] = {1, 3, 4, 5}, B] = {2, 4, 6, 8} Output: 1 2 3 4 4 5 6 8 Input: A[] = {5, 8, 9}, B[] = {4, 7, 8} Output: 4 5 7 8 8 9 Approach: The given problem, mergin
6 min read
Efficient way to initialize a priority queue
STL Priority Queue is the implementation of Heap Data Structure. By default, it's a max heap, and can be easily for primitive data types. There are some important applications of it which can be found in this article. Priority queue can be initialized in two ways either by pushing all elements one by one or by initializing using their constructor.
7 min read
Indexed Priority Queue with Implementation
Priority queue is a data structure in which data is stored on basis of its priority. In an Indexed Priority Queue, data is stored just like standard priority queue and along with this, the value of a data can be updated using its key. It is called "indexed" because a hash map can be used to store the index in container using the key of key-value pa
8 min read
Extracting last element of a Priority Queue without traversing
The Task is to extract the last element of the priority queue without traversing it. Approach: This problem can be solved using a Double-ended priority queue, a double-ended priority queue supports operations of both max heap (a max priority queue) and min heap (a min priority queue). The operations are: getMax(): Returns maximum element.getMin():
7 min read
How to implement Priority Queue - using Heap or Array?
A Priority Queue is a data structure that allows you to insert elements with a priority, and retrieve the element with the highest priority. You can implement a priority queue using either an array or a heap. Both array and heap-based implementations of priority queues have their own advantages and disadvantages. Arrays are generally easier to impl
15+ min read
Maximum Profit By Choosing A Subset Of Intervals (Using Priority-Queue)
Given a list intervals of n intervals, the ith element [s, e, p] denotes the starting point s, ending point e, and the profit p earned by choosing the ith interval. Find the maximum profit one can achieve by choosing a subset of non-overlapping intervals. Two intervals [s1, e1, p1] and [s2, e2, p2] are said to be non-overlapping if [e1 ? s2] and [s
8 min read
STL Priority Queue for Structure or Class
STL priority_queue is the implementation of Heap Data-structure. By default, it's a max heap and we can easily use it for primitive datatypes. There are some important applications of it which can be found here Prerequisite: Prioirty_queue Basics In this article, we will see how can we use priority_queue for custom datatypes like class or structure
3 min read
Priority queue of pairs in C++ with ordering by first and second element
Priority Queue: Priority queue is the extension of the queue in which elements associated with priority and elements having higher priority is popped first. Priority queue can contain elements with various data types such as integer, pair of integers, custom data type. But one thing is common that there is one element that defines the priority of t
5 min read
Implementation of Priority Queue in Javascript
Priority Queue is an extension of Queue having some properties as follows: Each element of the priority queue has a priority associated with it.Elements are added to the queue as per priority.Lowest priority elements are removed first.We can design a priority queue using two approaches in the first case we can add the queue element at the end of th
9 min read
Maximize array sum after K negations using Priority Queue
Given an array of size n and a number k. We must modify array K number of times. Here modify array means in each operation we can replace any array element arr[i] by -arr[i]. We need to perform this operation in such a way that after K operations, sum of array must be maximum? Examples: Input : arr[] = {-2, 0, 5, -1, 2} K = 4 Output: 10 // Replace
5 min read
Multiple comparisons in a C++ priority queue?
What is a Priority Queue? A Priority Queue is an abstract data type that is similar to a queue, and every element has some priority value associated with it. The priority of the elements in a priority queue determines the order in which elements are served (i.e., the order in which they are removed). If in any case, the elements have the same prior
5 min read
Implement the insert and delete functions on Priority queue without Array
A priority Queue is a type of queue in which every element is associated with a priority and is served according to its priority. We will use two popular data structures for implementing priority queues without arrays - Fibonacci HeapBinomial HeapFibonacci Heap:Fibonacci heap is a heap data structure that is composed of a collection of min-heap-ord
15+ min read
How to implement stack using priority queue or heap?
How to Implement stack using a priority queue(using min heap)? Asked In: Microsoft, Adobe.  Solution: In the priority queue, we assign priority to the elements that are being pushed. A stack requires elements to be processed in the Last in First Out manner. The idea is to associate a count that determines when it was pushed. This count works as a k
6 min read
Priority Queue using Binary Heap
Priority Queue is an extension of the queue with the following properties:   Every item has a priority associated with it.An element with high priority is dequeued before an element with low priority.If two elements have the same priority, they are served according to their order in the queue.A Binary Heap is a Binary Tree with the following proper
15+ min read
Priority Queue using Linked List
Implement Priority Queue using Linked Lists. push(): This function is used to insert a new data into the queue.pop(): This function removes the element with the highest priority from the queue.peek() / top(): This function is used to get the highest priority element in the queue without removing it from the queue.Priority Queues can be implemented
12 min read