Abstract Data Type

Priority Queue (PQ)

A priority queue is just a list of Queues sorted by priority. Depending on how the priority queue is implemented, you have different time complexities.

You can implement it using Array, Linked List, Vector, but the most natural choice is a Heap (Data Structure).

Pasted image 20220402165233.png

Links

C++

By Default, the C++ priority queue is a Max Heap and uses C++ Vector (see reference).

priority_queue<int> q;
q.push(3);
q.push(5);
q.push(7);
q.push(2);
cout << q.top() << "\n"; // 7
q.pop();
cout << q.top() << "\n"; // 5
q.pop();
q.push(6);
cout << q.top() << "\n"; // 6
q.pop();

If we want to create a priority queue that supports finding and removing the smallest element, we can do it as follows:

priority_queue<int, vector<int>,greater<int>> q;

Priority queues allow for duplicate values to be stored.

You can also implement a Priority Queue using a Heap.

For a priority queue of key-pairs, you can us the following:

# Max heap
priority_queue<pair<int, int>> pq;
 
 
# Min Heap
typedef pair<int, int> pi;
priority_queue<pi, vector<pi>, greater<pi> > pq;

NOTE: This is still different from an Ordered Map.

Why do we implement a priority queue with a heap?

We get insertion time and deletion time on average of , unlike a BST which is . So then why aren’t heaps used more often? Well, like in an Ordered Map, we need the keys to be ordered, and access every key in an ordered fashion.

Priority queues allow for duplicate values to be stored.