PriorityQueue
A
priority queue is a data structure similar to a queue, but where every element has priority associated. At any given moment the object with less (or most) priority is retrieved.
It's usually implemented using a
heap. Our version, based on the work of
BenDi, uses a
binary heap in a flat List, and instead of setting priority explicitly for each element we use IComparable<T> interface of Comparison<T> delegate. Let's see what it looks like!
public class PriorityQueue<T>
{
List<T> list = new List<T>();
Comparison<T> comparer;
public PriorityQueue():this(Comparer<T>.Default.Compare)
public PriorityQueue(IComparer<T> comparer)
public PriorityQueue(Comparison<T> comparer)
public int Count{get;}
public bool Empty{get;}
public int Push(T element)
public void PushAll(IEnumerable<T> elements)
public T Pop()
public T Peek()
public void Update(T element)
public bool Contains(T element)
public void Clear()
}
Example:
PriorityQueue<int> numbers = new PriorityQueue<int>();
numbers.Push(1);
numbers.Push(10);
numbers.Push(8);
numbers.Push(12);
numbers.Push(4);
numbers.Push(54);
while (!numbers.Empty)
Console.Write(numbers.Pop() + ", ");
Example using an explicit IComparer (LambdaComparer):
PriorityQueue<string> numbers = new PriorityQueue<string>(new LambdaComparer<string, int>(s => s.Length));
numbers.Push("Teutons");
numbers.Push("Mongols");
numbers.Push("Persians");
numbers.Push("Sarracens");
numbers.Push("Goths");
numbers.Push("Japanese");
numbers.Push("Celts");
numbers.Push("Chinese");
numbers.Push("Wikings");
numbers.Push("Britons");
numbers.Push("Turks");
numbers.Push("Franks");
numbers.Push("Byzantines");
while (!numbers.Empty)
Console.WriteLine(numbers.Pop());
Note that, in the current implementation, the priority is the only information taken into account, not the order they where introduced.