In this article, we are going to learn about implementing priority queues in C#.
Heaps are a special Tree-based data structure in which the tree is a complete binary tree. Generally, Heaps can be of two types: <ul><li>Max - Heap: the key present at the root node must be greatest among the keys present at all of it’s children.</li> <li>Min - Heap: the key present at the root node must be smallest among the keys present at all of it’s children.</li> </ul> In many languages such as C++ or Java, we already have a library which implements heaps. They are called priority queues. They are very useful as they can do certain tasks faster than other data structures. In C#, we do not have in priority queue library. So, we need to implement it ourselves.
Create a generic class PriorityQueue
as below:
public class PriorityQueue {
class Node {
public int Priority { get; set; }
public T Object { get; set; }
}
List queue = new List();
int heapSize = -1;
bool _isMinPriorityQueue;
public int Count { get { return queue.Count; } }
public PriorityQueue(bool isMinPriorityQueue = false) {
_isMinPriorityQueue = isMinPriorityQueue;
}
public void Enqueue(int priority, T obj){...}
public T Dequeue(){...}
public void UpdatePriority(T obj, int priority){...}
public bool IsInQueue(T obj){...}
private void BuildHeapMax(int i){...}
private void BuildHeapMin(int i){...}
private void MaxHeapify(int i){...}
private void MinHeapify(int i){...}
private void Swap(int i, int j) {
var temp = queue[i];
queue[i] = queue[j];
queue[j] = temp;
}
private int ChildL(int i) {
return i * 2 + 1;
}
private int ChildR(int i) {
return i * 2 + 2;
}
}
</code></pre>
MaxHeapify and MinHeapify methods are heap sorting.
We know these functions are required to maintain max and min heaps.
We will call these methods in each deletion.
private void MaxHeapify(int i) {
int left = ChildL(i);
int right = ChildR(i);
int heighst = i;
if (left <= heapSize && queue[heighst].Priority < queue[left].Priority)
heighst = left;
if (right <= heapSize && queue[heighst].Priority < queue[right].Priority)
heighst = right;
if (heighst != i) {
Swap(heighst, i);
MaxHeapify(heighst);
}
}
private void MinHeapify(int i) {
int left = ChildL(i);
int right = ChildR(i);
int lowest = i;
if (left <= heapSize && queue[lowest].Priority > queue[left].Priority)
lowest = left;
if (right <= heapSize && queue[lowest].Priority > queue[right].Priority)
lowest = right;
if (lowest != i) {
Swap(lowest, i);
MinHeapify(lowest);
}
}
Two methods BuildHeapMax and BuildHeapMin we will call in every insertion to make sure Heap property
is maintained.
private void BuildHeapMax(int i) {
while (i >= 0 && queue[(i - 1) / 2].Priority < queue[i].Priority) {
Swap(i, (i - 1) / 2);
i = (i - 1) / 2;
}
}
private void BuildHeapMin(int i) {
while (i >= 0 && queue[(i - 1) / 2].Priority > queue[i].Priority) {
Swap(i, (i - 1) / 2);
i = (i - 1) / 2;
}
}
Now let's implement Enqueue method:
public void Enqueue(int priority, T obj) {
Node node = new Node() { Priority = priority, Object = obj };
queue.Add(node);
heapSize++;
//Maintaining heap
if (_isMinPriorityQueue)
BuildHeapMin(heapSize);
else
BuildHeapMax(heapSize);
}
Enqueue method first inserts object in list then calls BuildHeapMax or BuildHeapMin methods
based on whether queue is Min-Queue or Max-Queue.
public T Dequeue() {
if (heapSize > -1) {
var returnVal = queue[0].Object;
queue[0] = queue[heapSize];
queue.RemoveAt(heapSize);
heapSize--;
//Maintaining lowest or highest at root based on min or max queue
if (_isMinPriorityQueue)
MinHeapify(0);
else
MaxHeapify(0);
return returnVal;
}
else
throw new Exception("Queue is empty");
}
Dequeue method returns first object in queue and places last element
at first then it calls MinHeapify or MaxHeapify methods to maintain heap.
Let's run above code:
static void Main(string[] args) {
PriorityQueue queue = new PriorityQueue();
Random rnd = new Random();
//enqueue
for (int i = 0; i < 10; i++) {
int x = rnd.Next(3);
queue.Enqueue(x, x);
}
//dequeue
while (queue.Count > 0) {
Console.Write(queue.Dequeue()+" ");
}
Console.WriteLine();
}
</code></pre>
Output:
2 2 2 2 1 1 1 1 0 0
We can see above output is prioritized.
There are two additional methods UpdatePriority and IsInQueue that we will implement.
public void UpdatePriority(T obj, int priority) {
int i = 0;
for (; i <= heapSize; i++) {
Node node = queue[i];
if (object.ReferenceEquals(node.Object, obj)) {
node.Priority = priority;
if (_isMinPriorityQueue) {
BuildHeapMin(i);
MinHeapify(i);
}
else {
BuildHeapMax(i);
MaxHeapify(i);
}
}
}
}
public bool IsInQueue(T obj) {
foreach (Node node in queue)
if (object.ReferenceEquals(node.Object, obj))
return true;
return false;
}
Above methods can be used to update priority of an object and finding an object in queue.
Task
Priority Queue is already defined in the editor below. Use Priority Queue to complete the following task:
Given an array of integers. Perform the following operations as directed in the editor below.