Priority queues_, _also called heaps,are an oft-misunderstood and underestimated concept in computer science. Though they are very simple, priority queues can serve as powerful tools to solve some of the well-known problems in computer science.

This article focuses on the basic concept of priority queues, their usage in C++, and applications to some of the most important problems.


The Concept Behind Priority Queues

As the name suggests, a priority queuecontains elements having a priority associated with them. Let’s start by taking a simple example.

Consider we have a list of grocery items and a priority attached to them. Let’s associate them as key-value pairs inserted into a priority queue, as shown below:

Image for post

List of grocery Items with priority

Tomatoes are at the top of the queue and have the highest priority, followed by NoodlesRice, and Wheat_. Let’s saywe want to push an item called Cakewith priority equal to10._When we push Cake into the priority queue, the queue checks if the item has a priority greater than that of Tomatoes (7). If yes, then it is inserted at the top of queue. The new queue is shown below:

Image for post

Cake added at the top of the priority queue

Now let’s say we want to push another grocery item (Chocolate)with priority equal to 2. In this case, the priority of Chocolate (2) is lower than the priority of Cake (10). So the queue pops the item Cake and checks for the next item Tomatoes (7). The case is similar to Cake — the queue pops out Tomatoes. The same rule applies to Noodles (5) and Rice (3).

#computers #technology #programming #data science

The Importance of Priority Queues
1.45 GEEK