Implement a simple priority queue

.NET framework does not have a priority queue built-in. There are several open source implementations. If you do not want to reference an entire library, it is fairly easy to implement one yourself. Many priority queue implementations use heap. However, if the number of levels of priorities is small, it is actually very easy and efficient to implement priority queues using an array of queues. There is a queue implementation in the .net framework.

My implementation is in the code below. The enum QueuePriorityEnum contains the number of levels of priorities. It is picked up automatically by the PriorityQueue class. The queue support 3 operations: Enqueue, Dequeue and Count. There behavior is modeled after the Queue class in the .net framework.

 

using System;
using System.Collections.Generic;
using System.Linq;

namespace MyNamespace
{
    // Modify this enum to add number of levels. It will picked up automatically
    enum QueuePriorityEnum
    {
        Low = 0,
        High =1
    }

    class PriorityQueue<T>
    {
        Queue<T>[] _queues;

        public PriorityQueue()
        {
            int levels = Enum.GetValues(typeof(QueuePriorityEnum)).Length;
            _queues = new Queue<T>[levels];
            for (int i = 0; i < levels; i++)
            {
                _queues[i] = new Queue<T>();
            }
        }

        public void Enqueue(QueuePriorityEnum priority, T item)
        {
	    _queues[(int)priority].Enqueue(item);
        }

        public int Count
        {
            get
            {
                return _queues.Sum(q => q.Count);
            }
        }

        public T Dequeue()
        {
	    int levels = Enum.GetValues(typeof(QueuePriorityEnum)).Length;
	    for (int i = levels - 1; i > -1; i--)
	    {
		if (_queues[i].Count > 0)
		{
			return _queues[i].Dequeue();
		}
	    }
            throw new InvalidOperationException("The Queue is empty. ");
        }
    }
}

No Comments