Skip to content

Instantly share code, notes, and snippets.

@hearsid
Created February 11, 2019 09:07
Show Gist options
  • Save hearsid/807b918cb3c8edfc116cad362caffc02 to your computer and use it in GitHub Desktop.
Save hearsid/807b918cb3c8edfc116cad362caffc02 to your computer and use it in GitHub Desktop.
Priority queue simple implementation in C#
public class PrioQueue<T>
{
int total_size;
SortedDictionary<int, Queue<T>> storage;
public PrioQueue()
{
this.storage = new SortedDictionary<int, Queue<T>>();
this.total_size = 0;
}
public bool IsEmpty()
{
return (total_size == 0);
}
public object Dequeue()
{
if (IsEmpty())
{
throw new Exception("Please check that priorityQueue is not empty before dequeing");
}
else
foreach (Queue<T> q in storage.Values)
{
// we use a sorted dictionary
if (q.Count > 0)
{
total_size--;
return q.Dequeue();
}
}
Debug.Assert(false, "not supposed to reach here. problem with changing total_size");
return null; // not supposed to reach here.
}
// same as above, except for peek.
public object Peek()
{
if (IsEmpty())
throw new Exception("Please check that priorityQueue is not empty before peeking");
else
foreach (Queue<T> q in storage.Values)
{
if (q.Count > 0)
return q.Peek();
}
Debug.Assert(false, "not supposed to reach here. problem with changing total_size");
return null; // not supposed to reach here.
}
public object Dequeue(int prio)
{
total_size--;
return storage[prio].Dequeue();
}
public void Enqueue(T item, int prio)
{
if (!storage.ContainsKey(prio))
{
storage.Add(prio, new Queue<T>());
}
storage[prio].Enqueue(item);
total_size++;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment