View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Priority Queue in Data Structure: Characteristics, Types & Implementation

By Rohit Sharma

Updated on Mar 07, 2025 | 14 min read | 59.6k views

Share:

How do Google Maps find the fastest route to your destination? It uses a priority queue in data structure to make this possible. A great priority queue example is 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 in data structure 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.

Priority Queue Example in Data Structure

Let’s consider a priority queue example in data structure using a min-priority queue, where elements are arranged in ascending order:

  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 in Data Structure

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

  • Priority Assignment:
    Each element in the priority queue in data structure 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.

Priority Queue 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.

Priority Queue 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.

Priority Queue Example:

Consider a priority queue example 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 queue in data structure 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 in data structure 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).
background

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree18 Months
View Program

Placement Assistance

Certification8-8.5 Months
View Program

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 in data structure. 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 in data structure 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 in data structure 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 in Data Structure

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

1. CPU Scheduling

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

Priority Queue 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.

Priority Queue 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.

Priority Queue 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.

Priority Queue 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.

Priority Queue 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.

Priority Queue 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.

Priority Queue 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!

Accelerate your career with Data Science courses from top universities. Join today to earn Executive PG, Advanced Certificates, or Master’s Programs!

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?

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

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

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

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

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

7. What are the different types of priority queues?

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

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

10. What is a priority queue of lists?

11. Which data structure is best for implementing a queue?

Rohit Sharma

697 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

Start Your Career in Data Science Today

Top Resources

Recommended Programs

upGrad Logo

Certification

3 Months

View Program
Liverpool John Moores University Logo
bestseller

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree

18 Months

View Program
IIIT Bangalore logo
bestseller

The International Institute of Information Technology, Bangalore

Executive Diploma in Data Science & AI

Placement Assistance

Executive PG Program

12 Months

View Program