Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Priority Queue in Data Structure: Characteristics, Types & Implementation

Updated on 19 November, 2024

59.29K+ views
14 min read

How do Google Maps find the fastest route to your destination? It uses a priority queue in data structure to make this possible. For instance, Dijkstra’s Shortest Path algorithm uses a min priority queue to rank all possible paths based on their distance. The path with the highest priority, often the shortest, is chosen as the best route.

A priority queue is a special data structure that processes elements based on their priority instead of the order they are added. This makes it different from a regular queue and incredibly useful in applications like navigation, task scheduling, and more.

In this blog, we’ll explore:

  • What makes priority queues unique.
  • The types of priority queues data structure.
  • How to implement them step by step.

Let’s understand why priority queues are so important in solving real-world problems!

Check out: Free Python Course with Certification

What is a Priority Queue in Data Structure?

A priority queue is an abstract data type (ADT) that organizes elements based on their priority rather than the order in which they were added. Unlike a regular queue, which follows a first-in-first-out (FIFO) order, a priority queue processes the element with the highest priority first. This makes it a versatile tool for handling scenarios where priority matters more than sequence.

Example Behavior

Let’s consider a priority queue with values 1, 3, 4, 8, 14, 22 arranged in ascending order (min-priority queue):

  1. Initial Queue: 1,3,4,8,14,22
  2. Operation: poll() removes the highest priority element (smallest value).
    Result: 3,4,8,14,22
  3. Operation: add(2) inserts a new element.
    Result: 2,3,4,8,14,22

Characteristics of a Priority Queue

Unlike a standard queue, where elements are processed in the order they arrive, a priority queue ensures that high-priority items are handled first. Here are its core characteristics:

  • Priority Assignment:
    Each element in the priority queue is associated with a priority value that determines its position. Higher-priority elements are placed ahead of lower-priority ones.
  • Priority-Based Deletion:
    Elements are dequeued based on their priority. The highest-priority item is always removed first, regardless of when it was added to the queue.
  • FIFO for Identical Priorities:
    When two or more elements have the same priority, they are dequeued in the order they were inserted, following the first-in, first-out (FIFO) rule.

Why Priority Queues Stand Out?

  • Efficient Task Management: Handles tasks by urgency or importance, making it ideal for scheduling, navigation, and algorithmic operations.
  • Dynamic Organization: Continuously reorganizes elements to ensure the highest priority items are always accessible.
  • Fair Processing: Maintains fairness by adhering to FIFO rules for elements with equal priority.

Example in Action

In a hospital’s emergency room, a patient with a critical condition would be treated first (highest priority). If two patients have similar conditions, the one who arrived is attended to first.

Priority queues are essential in scenarios requiring efficient and organized task processing, ensuring that the most critical items are addressed without delays.

What are the Different Types of Priority Queues?

A priority queue organizes elements based on their assigned priority, and the type of priority queue determines how these priorities are interpreted. There are two primary types of priority queues: ascending order priority queues and descending order priority queues. These structures differ in how they assign priority and process elements. Let’s explore them in detail.

1. Ascending Order Priority Queue

In an ascending order priority queue in data structure, elements with lower values are considered higher priority. This means that when dequeuing, the smallest value is removed first. The priority is inversely proportional to the numerical value of the elements.

Example:

Consider a priority queue with elements: 2, 4, 6, 8, 10.

  • The queue arranges the elements in ascending order: 2, 4, 6, 8, 10.
  • 2 has the highest priority, so it will be dequeued first.
  • Subsequent operations continue to remove elements in ascending order of their values.

Applications:

  • Commonly used in pathfinding algorithms, such as Dijkstra’s algorithm, where smaller distances or costs must be processed first.
  • Suitable for priority-based scheduling where tasks with lower numerical identifiers or lower resource requirements need to be handled first.

Implementation Notes:

  • Often implemented using min-heaps, as they allow efficient retrieval and deletion of the smallest value.
  • binary heap is typically used, providing logarithmic time complexity (O(log⁡n)) for both insertion and deletion operations.

2. Descending Order Priority Queue

In a descending order priority queue, elements with higher values are given precedence. This means that the largest value is dequeued first. The priority is directly proportional to the numerical value of the elements.

Example:

Consider a priority queue with elements: 1, 2, 3, 4, 5, 9.

  • The queue arranges the elements in descending order: 9, 4, 5, 3, 2, 1.
  • 45 has the highest priority, so it will be dequeued first.
  • Subsequent operations remove elements in descending order of their values.

Applications:

  • Frequently used in event-driven systems or real-time task scheduling, where higher-priority tasks (e.g., tasks with greater urgency or importance) must be handled first.
  • Useful in Prim’s algorithm for constructing a minimum spanning tree, where edges with higher weights are prioritized.

Implementation Notes:

  • Typically implemented using max-heaps, which efficiently provide the largest value.
  • A max-heap, structured as a binary tree, ensures logarithmic time complexity (O(log⁡n)) for insertions and deletions.


Key Differences Between Ascending and Descending Priority Queues

Feature

Ascending Order Priority Queue

Descending Order Priority Queue

Priority Rule

Lower value = Higher priority

Higher value = Higher priority

First Element Dequeued

Smallest value

Largest value

Common Implementation

Min-heap

Max-heap

Primary Use Case

Pathfinding, cost-efficient operations

Task scheduling, urgent tasks management

Implementation of Priority Queue in Data Structure

Priority queues can be implemented using various data structures. Each method offers distinct advantages and trade-offs, depending on the use case. 

1. Linked List Implementation

A linked list can implement a priority queue by maintaining elements in an order based on their priority. New elements are inserted at the correct position to preserve the order.

How It Works:

  • New elements are inserted into the list at the correct position to maintain priority order.
  • The head of the list always contains the element with the highest priority, making deletion O(1).
  • Traversing the list during insertion ensures correct placement, with complexity O(n).

Problem Statement:

Implement a priority queue in data structure using a linked list where elements are inserted based on their priority, and the highest-priority element can be dequeued efficiently.

Code Implementation (C++):

cpp

#include <bits/stdc++.h>
using namespace std;

// Node structure for the priority queue
struct Node {
    int data;
    int priority;
    Node* next;
};

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

// Function to remove the element with the highest priority
void pop(Node** head) {
    Node* temp = *head;
    *head = (*head)->next;
    delete temp;
}

// Function to add an element into the priority queue
void push(Node** head, int d, int p) {
    Node* temp = newNode(d, p);

    // If the queue is empty or new node has higher priority than the head
    if (*head == nullptr || (*head)->priority < p) {
        temp->next = *head;
        *head = temp;
    } else {
        Node* start = *head;
        while (start->next != nullptr && start->next->priority >= p) {
            start = start->next;
        }
        temp->next = start->next;
        start->next = temp;
    }
}

// Function to get the element with the highest priority
int peek(Node* head) {
    return head->data;
}

// Driver code
int main() {
    Node* pq = nullptr;
    push(&pq, 10, 2);
    push(&pq, 20, 4);
    push(&pq, 30, 3);
    push(&pq, 40, 1);

    while (pq != nullptr) {
        cout << "Top element: " << peek(pq) << endl;
        pop(&pq);
    }

    return 0;
}

Output:

Explanation of Output:

  • The elements are dequeued in the order of their priority (highest first).
  • 20 is dequeued first as it has the highest priority (4).
  • The next elements 3010, and 40 are dequeued in descending order of priority.

Complexity:

  • Insertion: O(n) (due to scanning for correct position).
  • Deletion: O(1) (removing the head).

Use Cases:

  • Suitable for applications requiring flexible insertion and retrieval.
  • Not ideal for large datasets due to O(n) insertion time.

2. Binary Heap Implementation

binary heap is the most efficient way to implement a priority queue. It uses a complete binary tree structure, ensuring logarithmic time for insertion and deletion operations.

How It Works:

  • Use a max heap to always keep the element with the highest priority at the root.
  • Insertions are done by placing the new element at the end of the heap and adjusting its position using the heapify-up operation.
  • Deletion involves removing the root, replacing it with the last element, and performing a heapify-down operation to maintain the heap property.

Problem Statement:

Implement a priority queue in data structure using a binary heap, allowing efficient insertion and removal of the highest-priority element.

Code Implementation (C++):

cpp

#include <bits/stdc++.h>
using namespace std;

// Class for a max-heap-based priority queue
class PriorityQueue {
    vector<int> heap;

    // Heapify-down to maintain the heap property after deletion
    void heapifyDown(int idx) {
        int largest = idx;
        int left = 2 * idx + 1;
        int right = 2 * idx + 2;

        if (left < heap.size() && heap[left] > heap[largest]) largest = left;
        if (right < heap.size() && heap[right] > heap[largest]) largest = right;

        if (largest != idx) {
            swap(heap[idx], heap[largest]);
            heapifyDown(largest);
        }
    }

    // Heapify-up to maintain the heap property after insertion
    void heapifyUp(int idx) {
        if (idx == 0) return;
        int parent = (idx - 1) / 2;

        if (heap[idx] > heap[parent]) {
            swap(heap[idx], heap[parent]);
            heapifyUp(parent);
        }
    }

public:
    // Insert a new element
    void push(int val) {
        heap.push_back(val);
        heapifyUp(heap.size() - 1);
    }

    // Remove the element with the highest priority
    void pop() {
        if (heap.empty()) return;
        heap[0] = heap.back();
        heap.pop_back();
        heapifyDown(0);
    }

    // Get the element with the highest priority
    int peek() {
        return heap.empty() ? -1 : heap[0];
    }

    // Check if the queue is empty
    bool isEmpty() {
        return heap.empty();
    }
};

// Driver code
int main() {
    PriorityQueue pq;
    pq.push(10);
    pq.push(50);
    pq.push(30);
    pq.push(20);

    while (!pq.isEmpty()) {
        cout << "Top element: " << pq.peek() << endl;
        pq.pop();
    }

    return 0;
}

 

Output:

Explanation of Output:

  • The elements are dequeued in descending order of priority, as the max heap maintains the largest element at the root.
  • 50 is dequeued first, followed by 3020, and 10.
  • The heap ensures efficient insertion (O(log⁡n)) and removal (O(log⁡n)).

Complexity:

  • Insertion: O(log⁡n).
  • Deletion: O(log⁡n).
  • Peek: O(1).

Use Cases:

  • Ideal for applications like Dijkstra’s algorithm, Prim’s algorithm, and event scheduling.
  • Efficient for handling large datasets with dynamic updates.

3. Array-Based Implementation

Priority queues can also be implemented using arrays, either ordered or unordered.

How It Works:

  • In an unordered array, elements are appended at the end, and the highest-priority element is found during deletion.
  • In an ordered array, elements are inserted in sorted order to allow O(1) deletion of the highest-priority element.

Problem Statement:

Implement a priority queue using an array, where elements are stored with their priority values, and the highest-priority element is retrieved efficiently.

Code Implementation (C++):

cpp

#include <bits/stdc++.h>
using namespace std;

// Priority queue using unordered array
class PriorityQueue {
    vector<pair<int, int>> arr;

public:
    // Add an element with priority
    void push(int val, int priority) {
        arr.push_back({priority, val});
    }

    // Remove the element with the highest priority
    void pop() {
        auto it = max_element(arr.begin(), arr.end());
        arr.erase(it);
    }

    // Get the element with the highest priority
    int peek() {
        auto it = max_element(arr.begin(), arr.end());
        return it->second;
    }

    // Check if the queue is empty
    bool isEmpty() {
        return arr.empty();
    }
};

// Driver code
int main() {
    PriorityQueue pq;
    pq.push(10, 2);
    pq.push(20, 5);
    pq.push(15, 3);

    while (!pq.isEmpty()) {
        cout << "Top element: " << pq.peek() << endl;
        pq.pop();
    }

    return 0;
}

Output:

Explanation of Output:

  • The highest-priority element is retrieved and removed in each operation.
  • The array stores priorities, allowing manual comparison during retrieval.

Complexity:

  • Unordered Array:
    • Insertion: O(1).
    • Deletion: O(n).
  • Ordered Array:
    • Insertion: O(n).
    • Deletion: O(1).

Use Cases:

  • Suitable for small datasets due to simplicity.
  • Inefficient for large or frequently updated datasets.

4. Binary Search Tree (BST) Implementation

A binary search tree (e.g., AVL or Red-Black Tree) can implement a priority queue by maintaining priority ordering in its structure.

How It Works:

  • Each node in the BST stores a priority value.
  • Insertion and deletion maintain the BST’s order, ensuring efficient retrieval of the highest/lowest priority.

Complexity:

  • Insertion: O(log⁡n).
  • Deletion: O(log⁡n).
  • Peek: O(1) (if root holds the highest priority).

Use Cases:

  • Suitable for applications requiring efficient search and ordered priority retrieval.
  • Trades-off simplicity for more memory overhead due to pointers.

Comparison of Implementations

Operation

Unordered Array

Ordered Array

Binary Heap

BST

Insert

O(1)

O(n)

O(log⁡n)

O(log⁡n)

Peek

O(n)

O(1)

O(1)

O(1)

Delete

O(n)

O(1)

O(log⁡n)

O(log⁡n)

Applications of Priority Queue

Priority queues are widely used in various systems and algorithms where prioritizing tasks or data is essential. Here are some common applications explained with practical examples to show their importance.

1. CPU Scheduling

Operating systems use priority queues to manage and schedule tasks based on their priority level.

Example:
In a computer system, processes are given priority levels. For instance:

  • Task A: Priority 3 (High)
  • Task B: Priority 2 (Medium)
  • Task C: Priority 1 (Low)

The CPU executes Task A first, followed by Task B and Task C. This ensures urgent tasks, such as system updates, are completed before less critical ones. Priority queues make this scheduling efficient and organized.

2. Graph Algorithms

Dijkstra’s Shortest Path Algorithm:

In this algorithm, a min-priority queue in data structure stores nodes based on their current shortest distance from the source. The node with the smallest distance is processed first.

Example:
In a navigation system, such as Google Maps, the shortest route is calculated using Dijkstra’s algorithm. A priority queue helps prioritize the next closest node to evaluate, ensuring the most efficient path is found.

Prim’s Minimum Spanning Tree Algorithm:

This algorithm uses a min-priority queue to select edges with the smallest weights to construct a minimum spanning tree.

Example:
In a network design, such as laying fiber-optic cables, Prim’s algorithm helps minimize costs by selecting the shortest connections between points.

3. Data Compression

Priority queues are used in Huffman coding, a popular method for reducing file sizes.

How It Works:
Huffman coding assigns shorter binary codes to frequently occurring characters and longer codes to less frequent ones. A min-priority queue combines the characters with the lowest frequencies first.

Example:
If a text contains the following character frequencies:

  • A: 5, B: 3, C: 2, D: 1.

The priority queue helps build a binary tree where characters with the smallest frequencies (C and D) are combined first. This tree generates efficient encodings, reducing the overall size of the compressed file.

4. Simulation

Priority queues are used in simulations to handle events based on their priority, ensuring critical tasks are processed before others.

Example:
In a hospital’s emergency room, patients are assigned priorities based on the severity of their condition:

  • Patient X: Critical condition (Priority 3)
  • Patient Y: Minor injury (Priority 1)
  • Patient Z: Serious injury (Priority 2)

A priority queue ensures Patient X is attended to first, followed by Patient Z and Patient Y.

Other Simulation Scenarios:

  • In banks, VIP customers are served first.
  • In gaming, critical game events are processed before less important ones.

5. Networking

Routers use priority queues to manage data packets. Critical packets, like live video streams or emergency signals, are prioritized over less important packets like file downloads.

Example:
If a router processes the following packets:

  • Live stream data: Priority 3
  • Email: Priority 1
  • Web browsing: Priority 2

The priority queue ensures live stream data is transmitted first, maintaining smooth performance for time-sensitive tasks.

6. Search Algorithms

A Search Algorithm:*

Priority queues are used in A* search to explore paths based on their cost and estimated distance to the target.

Example:
In robotic navigation, the algorithm uses a priority queue to evaluate the most promising paths first, reducing time and computation required to reach the destination.

Why Study Priority Queues in Data Structures?

Priority queues are a game-changer in data structures, powering solutions in navigation, scheduling, and more. Learning them sharpens your problem-solving skills and helps you tackle advanced algorithms like Dijkstra’s shortest path and Huffman coding.

Why Are Priority Queues Essential?

  • Boost Your Algorithm Game: Master the logic behind real-world systems like route optimization and data compression.
  • Career Edge: Knowledge of priority queues is a sought-after skill in roles like software developer, system architect, and data engineer.
  • Solve Real Problems: From task management in operating systems to simulations, priority queues make systems smarter and more efficient.

Learn Priority Queues with upGrad

Ready to strengthen your skills? upGrad’s expert-led courses in data structures and algorithms are the perfect way to grow.

Why Choose upGrad?

  • Work on real-world projects.
  • Get certifications recognized by top employers.
  • Learn from industry professionals.

Your next career move starts here! Explore upGrad Courses Now!

Elevate your expertise with our range of Popular Data Science Courses. Browse the programs below to discover your ideal fit.

Advance your in-demand data science skills with our top programs. Discover the right course for you below.

Explore popular articles related to data science to enhance your knowledge. Browse the programs below to find your ideal match.

Frequently Asked Questions (FAQs)

1. What is the difference between a normal queue and a priority queue?

A normal queue processes elements in the order they are added, following the first-in, first-out (FIFO) rule. A priority queue processes elements based on their priority, where higher-priority elements are dequeued before lower-priority ones, regardless of when they were added.

2. Which data structures are best for implementing priority queues?

Binary heaps (min-heaps or max-heaps) are the most efficient choice for implementing priority queues because they allow quick insertions and deletions (O(log⁡n)). Other options include linked lists, arrays, and binary search trees, depending on the size of the dataset and specific requirements.

3. Can a priority queue have elements with the same priority?

Yes, elements in a priority queue can share the same priority. In such cases, they are typically dequeued in the order they were added, following the first-in, first-out (FIFO) rule for elements with equal priority.

4. How does a priority queue work in Dijkstra’s algorithm?

In Dijkstra’s algorithm, a min-priority queue stores nodes based on their shortest distance from the starting point. Nodes with the smallest distance are processed first, which helps efficiently find the shortest path to all other nodes in the graph.

5. What is the time complexity of a binary heap implementation of a priority queue?

For a binary heap implementation:

  • Insertion: O(log⁡n).
  • Deletion (removing the highest-priority element): O(log⁡n).
  • Peek (accessing the highest-priority element): O(1).

6. Why would you use a priority queue instead of a standard queue?

A priority queue is used when the order of processing is more important than the order of arrival. It is ideal for tasks like scheduling processes in an operating system or finding the shortest path in graph algorithms, where urgency or importance determines the order of execution.

7. What are the different types of priority queues?

Priority queues can be of two types:

  • Ascending Order Priority Queue: Elements with the smallest value have the highest priority and are dequeued first.
  • Descending Order Priority Queue: Elements with the largest value have the highest priority and are dequeued first.

8. Can you implement a priority queue using an array?

Yes, a priority queue can be implemented using an array. In an unordered array, new elements are added at the end, and the highest or lowest priority is found during deletion (O(n)). In an ordered array, elements are inserted in sorted order (O(n)O(n)O(n)), allowing for O(1) deletion of the highest-priority element.

9. How do max heaps and min heaps work in priority queues?

  • In a max heap, the root node contains the largest element, representing the highest priority. When the root is removed, the heap is restructured to maintain this property.
  • In a min heap, the root node contains the smallest element, representing the highest priority. The heap reorganizes itself to keep this property intact after an element is removed.

10. In what situations are priority queues commonly used?

Priority queues are often used in:

  • CPU scheduling: To handle tasks based on urgency.
  • Graph algorithms: Such as Dijkstra’s shortest path and Prim’s minimum spanning tree.
  • Data compression: Like Huffman coding.
  • Simulations: To process events in the order of their importance.
  • Networking: To ensure critical data packets are transmitted first.

11. How does the priority queue handle insertions and deletions differently than other data structures?

In a priority queue, elements are inserted in a way that maintains their order based on priority, not on when they were added. Deletions always target the highest-priority element, unlike standard queues that process elements based on the first-in, first-out or last-in, first-out rules.