Click here to Skip to main content
15,884,986 members
Articles / Mobile Apps / Windows Mobile
Article

Priority queue

Rate me:
Please Sign up or sign in to vote.
4.50/5 (23 votes)
28 Mar 20041 min read 221.5K   5.1K   55   41
Another addition to the System.Collections namespace - a priority queue, also known as a heap.

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

C#
/// We create a PQ, add some random numbers and retreive them in sorted order:

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

  • 30.3.04 - Inserted.
  • 31.3.04 - renamed the main class to BinaryPriorityQueue.

    Created IPriorityQueue interface.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
Germany Germany
I did my diploma in Dresden and Sydney where I dealt with algorithms, agents and other cool AI stuff. Now I moved to Frankfurt to work on my PhD dealing with software structures for artificial intelligence systems. If I can, I do things in C# and ASP.NET, but if I have to, my C++, Java and SQL are not that bad.
Long Live .NET.

Comments and Discussions

 
GeneralDanka !!! :) Pin
Samedi Ishmael Medivh25-Oct-14 10:53
Samedi Ishmael Medivh25-Oct-14 10:53 
GeneralThanks a lot Pin
majdaldin122-Apr-11 2:59
majdaldin122-Apr-11 2:59 
GeneralMy vote of 3 Pin
LassarRRRRRR17-Feb-11 5:01
LassarRRRRRR17-Feb-11 5:01 
GeneralMy vote of 4 Pin
s.hamed_rezvani12-Jan-11 3:48
s.hamed_rezvani12-Jan-11 3:48 
GeneralGeneric version Pin
Olmo del Corral12-Mar-09 11:01
Olmo del Corral12-Mar-09 11:01 
GeneralUpdated for non duplicate value in list. Pin
bestwasin2-Feb-09 5:26
bestwasin2-Feb-09 5:26 
Questionimplemntinig priority Quesues Pin
Member 331791728-Aug-08 7:42
Member 331791728-Aug-08 7:42 
Questionimplemntinig priority Quesues Pin
Member 331791728-Aug-08 7:35
Member 331791728-Aug-08 7:35 
NewsFast Priority Queue Implementation of Dijkstra Shortest Path Algorithm Pin
Tolga Birdal31-Mar-08 5:38
Tolga Birdal31-Mar-08 5:38 
Questionremove method Pin
belal_haija22-Mar-08 15:41
belal_haija22-Mar-08 15:41 
Questionhashtable Pin
warnockm20-Nov-07 15:03
warnockm20-Nov-07 15:03 
GeneralCorrection Pin
David Krantz14-Dec-06 23:49
David Krantz14-Dec-06 23:49 
GeneralA-Star Implementation Pin
CastorTiu22-Sep-06 21:02
CastorTiu22-Sep-06 21:02 
GeneralTake care while using multiple threads Pin
novak.pavel31-May-06 2:08
novak.pavel31-May-06 2:08 
QuestionDijsktra's algorithm Pin
vit.ruzicka26-May-06 5:01
vit.ruzicka26-May-06 5:01 
GeneralRe: Dijsktra's algorithm Pin
warnockm20-Nov-07 15:05
warnockm20-Nov-07 15:05 
GeneralRemove functionality Pin
bffgdggd6-Jan-06 3:59
bffgdggd6-Jan-06 3:59 
GeneralLicense for Priority Queue Pin
tosboy20-Dec-05 23:40
tosboy20-Dec-05 23:40 
Generalconfused re: updating Pin
vmy1-Jun-04 16:23
vmy1-Jun-04 16:23 
GeneralRe: confused re: updating Pin
BenDi3-Jun-04 1:34
BenDi3-Jun-04 1:34 
GeneralRe: confused re: updating Pin
James Kolpack12-Jan-06 6:35
James Kolpack12-Jan-06 6:35 
I also had a need to do this, so I derived a class which handles it.

It does this by using a key-value lookup (in mObjectIndex) and updating this after any operation on the queue. Note: this means changing the base class by 1) making sure all the methods this overriding are virtual and 2) renaming Update to UpdateIndex. Also, one of the constructors from the original is missing.

It definitely will take a performance hit to do these operations, but if you need it, here it is.

Kudos to BenDi for posting the base class.

///
/// Adds update functionality to objects in the priority queue
///

public class BinaryPriorityQueueWithUpdate : BinaryPriorityQueue
{
private Hashtable mObjectIndex;

///
/// Determines whether the specified BinaryPriorityQueue contains object.
///

/// <param name="obj" />The obj.
public bool ContainsObject(object obj)
{
return mObjectIndex.Contains(obj);
}

#region contructors
///
/// Initializes a new instance of the <see cref="BinaryPriorityQueueWithUpdate"> class.
///

public BinaryPriorityQueueWithUpdate() : base()
{
mObjectIndex = new Hashtable();
}

///
/// Initializes a new instance of the <see cref="BinaryPriorityQueueWithUpdate"> class.
///

/// <param name="comparer" />The comparer.
public BinaryPriorityQueueWithUpdate(IComparer comparer) : base(comparer)
{
mObjectIndex = new Hashtable();
}
///
/// Initializes a new instance of the <see cref="BinaryPriorityQueueWithUpdate"> class.
///

/// <param name="capacity" />The capacity.
public BinaryPriorityQueueWithUpdate(int capacity) : base(capacity)
{
mObjectIndex = new Hashtable(capacity);
}

///
/// Initializes a new instance of the <see cref="BinaryPriorityQueueWithUpdate"> class.
///

/// <param name="comparer" />The comparer.
/// <param name="capacity" />The capacity.
public BinaryPriorityQueueWithUpdate(IComparer comparer, int capacity) : base(comparer, capacity)
{
mObjectIndex = new Hashtable(capacity);
}

#endregion

///
/// Get the smallest object and remove it.
///

/// <returns>The smallest object
public override object Pop()
{
mObjectIndex.Remove(InnerList[0]);
if (InnerList.Count > 0)
{
mObjectIndex.Remove(InnerList[InnerList.Count-1]);
mObjectIndex.Add(InnerList[InnerList.Count-1], 0);
}

return base.Pop();
}

///
/// Push an object onto the PQ
///

/// <param name="obj" />The new object
/// <returns>
/// The index in the list where the object is _now_. This will change when objects are taken from or put onto the PQ.
///
public override int Push(object obj)
{
mObjectIndex.Add(obj, InnerList.Count);
return base.Push(obj);
}

///
/// Switches the elements.
///

/// <param name="i" />The i.
/// <param name="j" />The j.
protected override void SwitchElements(int i, int j)
{
object iObj = this.InnerList[i];
object jObj = this.InnerList[j];
mObjectIndex.Remove(iObj);
mObjectIndex.Remove(jObj);
mObjectIndex.Add(iObj, j);
mObjectIndex.Add(jObj, i);
base.SwitchElements (i, j);
}

///
/// Updates the specified obj.
///

/// <param name="obj" />The obj.
/// <param name="newObj" />The new obj.
public void Update(object obj, object newObj)
{
int index = (int) mObjectIndex[obj];
mObjectIndex.Remove(obj);
mObjectIndex.Add(newObj, index);
InnerList[index] = newObj;
base.UpdateIndex(index);
}

///
/// Updates the specified obj.
///

/// <param name="obj" />The obj.
public void Update(object obj)
{
int index = (int) mObjectIndex[obj];
base.UpdateIndex(index);
}
}
GeneralThanks!! Pin
abc8769-Apr-04 19:21
abc8769-Apr-04 19:21 
QuestionWhat is wrong with Queue? Pin
sandeman2-Apr-04 9:16
sandeman2-Apr-04 9:16 
AnswerRe: What is wrong with Queue? Pin
BenDi2-Apr-04 9:36
BenDi2-Apr-04 9:36 
GeneralRe: What is wrong with Queue? Pin
BenDi2-Apr-04 9:38
BenDi2-Apr-04 9:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.