Priority Queues with C#

A priority queue is a data structure that stores elements with associated priority values. It is an extension of a regular queue where elements are served based on their priority rather than their insertion order.

When you remove an item from a priority queue, the element with the highest priority is removed first. If two elements have the same priority, they are typically served in the order they were inserted.

Syntax

Following is the basic syntax for creating a priority queue class −

public class MyPriorityQueue<T> where T : IComparable<T> {
   private List<T> items;
   
   public void Enqueue(T item) { }
   public T Dequeue() { }
   public int Count { get; }
}

Basic Priority Queue Implementation

Let us implement a simple priority queue using a generic list. The items are stored in a list and sorted based on their natural ordering −

using System;
using System.Collections.Generic;

public class MyPriorityQueue<T> where T : IComparable<T> {
   private List<T> items;

   public MyPriorityQueue() {
      this.items = new List<T>();
   }

   public void Enqueue(T item) {
      items.Add(item);
      items.Sort(); // Sort to maintain priority order
   }

   public T Dequeue() {
      if (items.Count == 0)
         throw new InvalidOperationException("Priority queue is empty");
      
      T highestPriority = items[items.Count - 1]; // Last item after sorting
      items.RemoveAt(items.Count - 1);
      return highestPriority;
   }

   public int Count {
      get { return items.Count; }
   }

   public bool IsEmpty {
      get { return items.Count == 0; }
   }
}

class Program {
   public static void Main() {
      MyPriorityQueue<int> pq = new MyPriorityQueue<int>();
      
      pq.Enqueue(3);
      pq.Enqueue(1);
      pq.Enqueue(4);
      pq.Enqueue(2);

      Console.WriteLine("Priority Queue contents (highest first):");
      while (!pq.IsEmpty) {
         Console.WriteLine("Dequeued: " + pq.Dequeue());
      }
   }
}

The output of the above code is −

Priority Queue contents (highest first):
Dequeued: 4
Dequeued: 3
Dequeued: 2
Dequeued: 1

Priority Queue with Custom Objects

You can also create priority queues with custom objects by implementing the IComparable interface −

using System;
using System.Collections.Generic;

public class Task : IComparable<Task> {
   public string Name { get; set; }
   public int Priority { get; set; }

   public Task(string name, int priority) {
      Name = name;
      Priority = priority;
   }

   public int CompareTo(Task other) {
      if (other == null) return 1;
      return this.Priority.CompareTo(other.Priority);
   }

   public override string ToString() {
      return $"{Name} (Priority: {Priority})";
   }
}

class Program {
   public static void Main() {
      MyPriorityQueue<Task> taskQueue = new MyPriorityQueue<Task>();
      
      taskQueue.Enqueue(new Task("Low Priority Task", 1));
      taskQueue.Enqueue(new Task("High Priority Task", 5));
      taskQueue.Enqueue(new Task("Medium Priority Task", 3));
      taskQueue.Enqueue(new Task("Urgent Task", 4));

      Console.WriteLine("Processing tasks by priority:");
      while (!taskQueue.IsEmpty) {
         Task nextTask = taskQueue.Dequeue();
         Console.WriteLine("Processing: " + nextTask);
      }
   }
}

The output of the above code is −

Processing tasks by priority:
Processing: High Priority Task (Priority: 5)
Processing: Urgent Task (Priority: 4)
Processing: Medium Priority Task (Priority: 3)
Processing: Low Priority Task (Priority: 1)

Using Built-in PriorityQueue (C# 6.0+)

In modern C#, you can use the built-in PriorityQueue<TElement, TPriority> class available in .NET 6 and later −

using System;
using System.Collections.Generic;

class Program {
   public static void Main() {
      // Create priority queue with string elements and int priorities
      var pq = new PriorityQueue<string, int>();
      
      pq.Enqueue("Low priority task", 1);
      pq.Enqueue("High priority task", 5);
      pq.Enqueue("Medium priority task", 3);
      pq.Enqueue("Critical task", 10);

      Console.WriteLine("Processing tasks (lowest priority number first):");
      while (pq.Count > 0) {
         string task = pq.Dequeue();
         Console.WriteLine("Processing: " + task);
      }
   }
}

The output of the above code is −

Processing tasks (lowest priority number first):
Processing: Low priority task
Processing: Medium priority task
Processing: High priority task
Processing: Critical task

Key Operations

Operation Description Time Complexity
Enqueue(item) Adds an item to the priority queue O(n) for simple implementation
Dequeue() Removes and returns the highest priority item O(1) for simple implementation
Peek() Returns the highest priority item without removing it O(1)

Conclusion

Priority queues are essential data structures for scenarios where elements need to be processed based on their importance rather than arrival order. You can implement custom priority queues using lists and sorting, or use the built-in PriorityQueue class available in modern .NET versions for better performance.

Updated on: 2026-03-17T07:04:35+05:30

338 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements