Practice
Resources
Contests
Online IDE
New
Free Mock
Scaler
Practice
Improve your coding skills with our resources
Contests
Compete in popular contests with top coders
Scaler
Explore Offerings by SCALER

Begin your success journey!

Sign Up using
Full name *
Email *
Password *

By creating an account, I acknowledge that I have read and agree to InterviewBit’s Terms and Privacy Policy .

Welcome back!

Log In using
Email *
Password *

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.
All fields are mandatory
Current Employer *
Enter company name *
Graduation Year *
Select an option *
1992
1993
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
Phone Number *
OTP will be sent to this number for verification
+1 *
+1
Change Number
Phone Number *
OTP will be sent to this number for verification
+1 *
+1
Change Number
Graduation Year *
Graduation Year *
1992
1993
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
*Enter the expected year of graduation if you're student
Current Employer *
Company Name *
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