Introduction
Many algorithms - for instance Dijkstra's well-known search for the shortest path - run most efficient with a 'semi-sorted' list, which always has the smallest element up front. The most efficient structure for this purpose is a heap, also called priority queue.
Usage
The PriorityQueue
class is built in the guidelines of the System.Collections
namespace. Comparison is done through the IComparer
interface, or, if none is specified, through the IComparable
implementation of the provided objects. The objects in the PQ need not have all the same type but they have to be comparable with each other.
Next to the standard System.Collections
methods (Count
, Contains
, ... you name it), the PQ supports 3 main operations:
Push()
: This will add an object to the PQ, reforming the structure so that this element is at the front if it is the currently smallest. The complexity of the operation is O(ld n).
Pop()
: This will remove and return the current head of the PQ, which always is the smallest element. Complexity O(ld n).
Update()
: It might be necessary to change elements that are already in the queue. Because this is not very common (you need to find the element first), it can only be done by the explicit IList
implementation (the indexer should not be used in any other case). Once you set the indexer, the PQ will automatically reorder. Complexity O(ld n) (surprise;))
Example
IPriorityQueue PQ = new BinaryPriorityQueue();
Random R = new Random();
int i;
for(i=0;i<50;i++)
{
PQ.Push(R.Next(1000));
}
while(PQ.Count>0)
Console.WriteLine(PQ.Pop());
History