Search code examples
c#data-structuresqueue

C# Priority Queue


I'm looking for a priority queue with an interface like this:

class PriorityQueue<T>
{
    public void Enqueue(T item, int priority)
    {
    }

    public T Dequeue()
    {
    }
}

All the implementations I've seen assume that item is an IComparable but I don't like this approach; I want to specify the priority when I'm pushing it onto the queue.

If a ready-made implementation doesn't exist, what's the best way to go about doing this myself? What underlying data structure should I use? Some sort of self-balancing tree, or what? A standard C#.net structure would be nice.


Solution

  • If you have an existing priority queue implementation based on IComparable, you can easily use that to build the structure you need:

    public class CustomPriorityQueue<T>  // where T need NOT be IComparable
    {
      private class PriorityQueueItem : IComparable<PriorityQueueItem>
      {
        private readonly T _item;
        private readonly int _priority:
    
        // obvious constructor, CompareTo implementation and Item accessor
      }
    
      // the existing PQ implementation where the item *does* need to be IComparable
      private readonly PriorityQueue<PriorityQueueItem> _inner = new PriorityQueue<PriorityQueueItem>();
    
      public void Enqueue(T item, int priority)
      {
        _inner.Enqueue(new PriorityQueueItem(item, priority));
      }
    
      public T Dequeue()
      {
        return _inner.Dequeue().Item;
      }
    }