Introduction to Priority Queues. A beginners guide to Priority Queues in Programming.
Introduction
Today, we will learn about a new Data Structure called Priority Queue. As the name suggests, Priority Queue is a queue with some priority. The priority can be user defined.
We will have a look at what is a priority queue, where is it used, its syntax, and basic time complexities. So let's get started.
What is a Priority Queue.
Priority Queue is a data structure that works on the concepts of Heaps. Heaps means data stored in the form of a heap. The heap can be sorted in an ascending manner or a descending manner. They are called as min-heap and max-heap respectively.
We do not want to implement heap in our day to day programming that is why C++ and other languages have this in-built data structure called as priority queue. It makes life easy for us. By default, a priority queue is implemented as a max-heap. We can make slight changes in the syntax and convert it into a min-heap.
Uses of a Priority Queue
Priority Queue is an important data structure in a lot of algorithms like
- Djikstra's algorithm to find shortest path
- Data compression using Huffman's encoding
- The A* Search algorithm.
- Interrupt handling in Operating Systems
As we can see, it is a very important data structure. Not only in algorithms, priority queues are also an important data structure from an interview point of view.
Syntax and Functions of a Priority Queue
This is how a priority queue is declared in C++. (max-heap)
priority_queue<int>prque; // priority_queue<data_type>[name of the queue].
`
For a min-heap, use this syntax.
priority_queue<int,vector<int>,greater<int>> prque;
// priority_queue<data_type, vector<data_type>,greater<data_type>>
Looks a bit daunting but you will get the hang of it once you start applying it on a regular basis. Just like Stacks and Queues, you can access only the top-most data in a priority queue.
The prority-queue gives us a lot of in-built functions like push an element, pop an element, get the size of the queue, etc. Let's have a look at each one of them.
#include<bits/stdc++.h>
using namespace std;
int main()
{
// N = Current size of heap.
priority_queue<int>p; // A priority queue which stores data in descending order.
p.push(3); // Time Complexity: O(LogN)
p.push(5); // Time Complexity: O(LogN)
p.pop(); // Time Complexity: O(1)
cout<<p.size()<<endl;
cout<<p.empty()<<endl;
while(p.empty()==false) // to get all the elements of a priority queue
{
int x = p.top(); // gets the top-most element
cout<<x<<" ";
p.pop();
}
}
Conclusion.
Well, that's it. That is all you need to know about a priority queue in order to begin with it. Wherever you see a question asking for K Frequen, K Maximum, K Minimum, try thinking of a priority queue first. These are some general question types where a priortity queue can be used easily.
In the next article, we will have a look at a bit advanced data structure known as Binary Tree.