Practice
Resources
Contests
Online IDE
New
Free Mock
Events New Scaler
Practice
Improve your coding skills with our resources
Contests
Compete in popular contests with top coders
logo
Events
Attend free live masterclass hosted by top tech professionals
New
Scaler
Explore Offerings by SCALER

Priority Queue in C#

In this article, we are going to learn about implementing priority queues in C#.

Heaps

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.


Implementation

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.

Start solving Priority Queue in C# on Interview Code Editor
Hints
  • Complete Solution

Discussion


Loading...
Click here to start solving coding interview questions
Free Mock Assessment
Fill up the details for personalised experience.
Phone Number *
OTP will be sent to this number for verification
+1 *
+1
Change Number
Graduation Year *
Graduation Year *
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
*Enter the expected year of graduation if you're student
Current Employer
Company Name
College you graduated from
College/University Name
Job Title
Job Title
Engineering Leadership
Software Development Engineer (Backend)
Software Development Engineer (Frontend)
Software Development Engineer (Full Stack)
Data Scientist
Android Engineer
iOS Engineer
Devops Engineer
Support Engineer
Research Engineer
Engineering Intern
QA Engineer
Co-founder
SDET
Product Manager
Product Designer
Backend Architect
Program Manager
Release Engineer
Security Leadership
Database Administrator
Data Analyst
Data Engineer
Non Coder
Other
Please verify your phone number
Edit
Resend OTP
By clicking on Start Test, I agree to be contacted by Scaler in the future.
Already have an account? Log in
Free Mock Assessment
Instructions from Interviewbit
Start Test