The Wayback Machine - https://web.archive.org/web/20240723090919/https://www.geeksforgeeks.org/indexed-priority-queue-with-implementation/
Open In App

Indexed Priority Queue with Implementation

Last Updated : 29 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

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 pair input  as the key of hash map. This comes handy while implementing  Dijkstra’s Algorithm using min-heap. It can also be used in any other program where it is required to put key-value pairs in priority queue and along with it you need to update value of keys with push or pop function .

Operations in an Indexed Priority Queue: The operations which can be performed in Indexed Priority Queue are:

  1. push:  Adding key-value pair in Indexed Priority Queue according to its priority. Implementation: To do this, add the key value pair in container and then heapify on basis of value in key-value pair. Time Complexity: O( log(n) )
  2. pop:  Removing the highest priority key-value pair. Implementation: Remove top of heap and then heapify rest of the container. Time Complexity: O( log(n))
  3. top: Return Key-Value pair to user. Implementation: Return Key-Value pair which is at top of the heap. Time Complexity: O(1)
  4. size: Return the number of key-value pairs in the Indexed Priority Queue. Implementation: Keep a track if number of elements in queue in the class and return the variable when size() function is called. Time Complexity: O(1)
  5. empty: Return true when Indexed Priority Queue is empty. Implementation: Return true when number of elements variable is equal to zero. Time Complexity: O(1)
  6. changeAtKey: This function differentiate Indexed Priority Queue from standard priority queue. It takes two arguments from user, first is key and second is new value, and it update old value associated with the key to new value provided and update its position according to priority of new value. Implementation: Keep a hash-map whose key is key in key-value pair and it points to index of the key in container. When the function is called update the value at required index and position current element according to its priority and finally change index value in hash map. Time Complexity: O( log(n) )

Implementation of Indexed Priority Queue:

Indexed Priority Queue is implemented using binary heap, however it can also be implemented using Fibonacci heap or K-ary heap. 

There are four parameters to be passed while defining an instance of Indexed Priority Queue(two mandatories and two optional) which are:

  1. Data type of key:  This is the first parameter in the definition and it should be data type that can be hashed in hash map or user have pass his own hash function as fourth parameter. To learn more about hash function in hash map see this article.
  2. Data type of value: This is second parameter in definition.
  3. Comparator: This is third and optional parameter. By default Indexed Priority Queue will be implemented using max heap to change that user have to pass different comparator with its parameter (i.e. parameter of comparator) as the data type of value.
  4. Hash function: This is fourth parameter and required only when user pass custom data type (like a class) for key, then user have to pass his own hash function.

Below is the implementation of Indexed Priority Queue:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
template <class T1, class T2,
          class Comparator = less<T2>,
          class Hash = hash<T1> >
 
class indexed_priority_queue {
 
    // Storing indices of values using key
    unordered_map<T1, long long int, Hash> m;
 
    // Container
    vector<pair<T1, T2> > v;
 
    // Size
    long long numberOfElement;
 
    // Creating a instance of Comparator class
    Comparator comp;
 
    // Max Capacity
    long long capacity = LLONG_MAX;
 
    // Obtaining the index value from hash map
    long long int getValueIndex(T1 key)
    {
        if (m[key] == 0) {
            cout << "No Such Key Exist";
            return -1;
        }
        return v[m[key] - 1];
    }
 
    // heapify the container
    void heapify(vector<pair<T1, T2> >& v,
                 long long int heap_size,
                 long long index)
    {
        long long leftChild = 2 * index + 1,
                  rightChild = 2 * index + 2,
                  suitableNode = index;
 
        if (leftChild < heap_size
            && comp(v[suitableNode].second,
                    v[leftChild].second)) {
            suitableNode = leftChild;
        }
 
        if (rightChild < heap_size
            && comp(v[suitableNode].second,
                    v[rightChild].second)) {
            suitableNode = rightChild;
        }
 
        if (suitableNode != index) {
 
            // swap the value
            pair<T1, T2> temp = v[index];
            v[index] = v[suitableNode];
            v[suitableNode] = temp;
 
            // updating the map
            m[v[index].first] = index + 1;
            m[v[suitableNode].first]
                = suitableNode + 1;
 
            // heapify other affected nodes
            heapify(v, numberOfElement,
                    suitableNode);
        }
    }
 
public:
    indexed_priority_queue()
    {
        numberOfElement = 0;
        m.clear();
        v.clear();
    }
 
    void push(T1 key, T2 value)
    {
        if (numberOfElement == capacity) {
            cout << "Overflow";
            return;
        }
        if (m[key] != 0) {
            cout << "Element Already Exists";
            return;
        }
 
        // Adding element
        v.push_back(make_pair(key, value));
        numberOfElement++;
        m[key] = numberOfElement;
 
        long long index = numberOfElement - 1;
 
        // Comparing to parent node
        while (index != 0
               && comp(v[(index - 1) / 2].second,
                       v[index].second)) {
 
            // swap the value
            pair<T1, T2> temp = v[index];
            v[index] = v[(index - 1) / 2];
            v[(index - 1) / 2] = temp;
 
            // updating the map
            m[v[index].first] = index + 1;
            m[v[(index - 1) / 2].first]
                = (index - 1) / 2 + 1;
 
            // updating index in map
            index = (index - 1) / 2;
        }
    }
 
    void pop()
    {
        if (numberOfElement == 0) {
            cout << "UnderFlow";
            return;
        }
 
        // Removing element
        v.erase(v.begin());
        numberOfElement--;
        heapify(v, numberOfElement, 0);
    }
 
    pair<T1, T2> top() { return v[0]; }
 
    long long int size() { return numberOfElement; }
 
    bool empty() { return numberOfElement == 0; }
 
    void changeAtKey(T1 key, T2 value)
    {
        if (m[key] == 0) {
            cout << "No Such Key Exist";
            return;
        }
        long long index = m[key] - 1;
        v[index].second = value;
 
        // Comparing to child nodes
        heapify(v, numberOfElement, index);
 
        // Comparing to Parent Node
        while (index != 0
               && comp(v[(index - 1) / 2].second,
                       v[index].second)) {
 
            // swap the value
            pair<T1, T2> temp = v[index];
            v[index] = v[(index - 1) / 2];
            v[(index - 1) / 2] = temp;
 
            // updating the map
            m[v[index].first] = index + 1;
            m[v[(index - 1) / 2].first]
                = (index - 1) / 2 + 1;
 
            // updating index in map
            index = (index - 1) / 2;
        }
    }
};
 
void display(indexed_priority_queue<int, int> IPQ)
{
    indexed_priority_queue<int, int> temp = IPQ;
    while (!IPQ.empty()) {
        pair<int, int> tmp;
        tmp = IPQ.top();
        IPQ.pop();
        cout << "( " << tmp.first << ", "
             << tmp.second << " ) ";
    }
    cout << '\n';
}
 
// Driver Code
int main()
{
 
    // First parameter is key datatype
    // and it should be hashable
    // Second parameter is value datatype comparator
    // function (by default it implements maxheap)
    indexed_priority_queue<int, int> IPQ;
 
    // Check if empty
    cout << "Checking if initially the IPQ is empty\n";
    if (IPQ.empty())
        cout << "IPQ is empty\n";
    else
        cout << "IPQ is not empty\n";
 
    // Insertion
    cout << "Inserting pairs (2, 1), (3, 7), "
         << " (1, 0) and (4, 5)\n";
    IPQ.push(2, 1);
    IPQ.push(3, 7);
    IPQ.push(1, 0);
    IPQ.push(4, 5);
 
    // Printing the contents of IPQ
    cout << "IPQ: ";
    display(IPQ);
    cout << '\n';
 
    // Checking size and top after pushing
    cout << "Size: " << IPQ.size() << endl;
    cout << "Top: " << IPQ.top().first
         << ", " << IPQ.top().second
         << "\n\n";
 
    // Replace operation
    cout << "Changing value associated with"
         << " key 3 to 2 and 1 to 9\n";
    IPQ.changeAtKey(3, 2);
    IPQ.changeAtKey(1, 9);
 
    // Checking size and top after replacement
    cout << "Size: " << IPQ.size() << endl;
    cout << "Top: " << IPQ.top().first
         << ", " << IPQ.top().second
         << "\n\n";
 
    // Deleting 2 elements from IPQ
    cout << "Popping an element from IPQ: ";
    IPQ.pop();
    cout << "\nPopping an element from IPQ: ";
    IPQ.pop();
    cout << '\n\n';
 
    // Printing the contents of IPQ after deletion
    cout << "IPQ: ";
    display(IPQ);
    cout << '\n';
 
    // Checking size and top after pushing
    cout << "Size: " << IPQ.size() << endl;
    cout << "Top: " << IPQ.top().first
         << ", " << IPQ.top().second
         << "\n\n";
 
    return 0;
}


Output:Checking if initially the IPQ is empty IPQ is empty Inserting pairs (2, 1), (3, 7), (1, 0) and (4, 5) IPQ: ( 3, 7 ) ( 4, 5 ) ( 2, 1 ) ( 1, 0 ) Size: 4 Top: 3, 7 Changing value associated with key 3 to 2 and 1 to 9 Size: 4 Top: 1, 9 popping an element from IPQ: popping an element from IPQ: IPQ: ( 3, 2 ) ( 2, 1 ) Size: 2 Top: 3, 2


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
What is Priority Queue | Introduction to Priority Queue
A priority queue is a type of queue that arranges elements based on their priority values. Elements with higher priority values are typically retrieved before elements with lower priority values. In a priority queue, each element has a priority value associated with it. When you add an element to the queue, it is inserted in a position based on its
15+ 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
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
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
three90RightbarBannerImg