Click here to Skip to main content
Click here to Skip to main content

Priority queue

By , 28 Mar 2004
 

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

/// 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

About the Author

BenDi
Software Developer (Senior)
Germany Germany
Member
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.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralThanks a lotmembermajdaldin122 Apr '11 - 2:59 
GeneralMy vote of 3memberLassarRRRRRR17 Feb '11 - 5:01 
GeneralMy vote of 4members.hamed_rezvani12 Jan '11 - 3:48 
GeneralGeneric versionmemberOlmo del Corral12 Mar '09 - 11:01 
GeneralUpdated for non duplicate value in list.memberbestwasin2 Feb '09 - 5:26 
Questionimplemntinig priority QuesuesmemberMember 331791728 Aug '08 - 7:42 
hi ! i am implemnting a program that first
* make Queue_Adt
* create a program structure
1. Create a program structure. It contains a float ProgramAge (or creationTime), and two imtegers programNumber and priority_level. ProgramNumber is a just like a counter. Program age can have values 0<ProgramAge<20
2. Create three queues of type program: QueueADT<program> low, high and mid.
3. Create a function program getNextProgram(), that creates a program, randomly assigns values to its programAge and priority_level (0,1 or 2) and returns the program. It also assigns value to programNumber. let programNumber = 0 for first program, programNumber=1 for second and so on.
4. Get a program from getNextProgram(). Based on the priority of the program, select the queue for the program.
5. Once the queue is decided, insert the program into the queue depending on its ProgramAge. The program with the highest ProgramAge should be in front of the queue.
6. Repeat 4-5, 20 times.
7. Write the configuration of each queue into file. For example file should look something like:
 
High:
ProgramNumber = 2, ProgramAge=3.5
ProgramNumber = 4, ProgramAge=2

Mid:
ProgramNumber = 0, ProgramAge=13.2

Low:
ProgramNumber = 3, ProgramAge=4.0
ProgramNumber = 1, ProgramAge=3.0


 
but stuck in step " 5 " also help me out how to put that data on text file :
sample code of main class is given
                         #include <iostream.h>
                         #include <conio.h>
                        #include "Queue.cpp"
                                   #include <math.h>    // For time()

 

 
   class   Programm{
            private:
                int  prior_level,program_no;
                 float creation_time;
                public:
                Programm(){
 
                          program_no=0;
                }
 

                   void set_id()
                   {
                   program_no++;
                   }
                    void set_time()
                   {
                    //srand(time(0));
                   creation_time=(rand() % 20) + 1;
                   }
                   void set_prior()
                   {
                   prior_level=(rand() % 3) ;
                   }
 
                   int get_id()
                   {
                   return program_no;
                   }
                    float get_time()
                   {
                   return creation_time;
 
                   }
                   int get_prior()
                   {
                   return prior_level;
                   }
 

                   };//class

                     void  main()
 
                      {
 

 

                        Queue<Programm> low,high,medium;
                        Programm p;
                        int pl,hl,ml=0;
 
                    for (int i=0;i<=20;i++)
                      {
                               p.set_prior();
                             if(p.get_prior()==0)
                             {
 

 

                             low.enQueue(p);
 
                            cout<<"the no of element in low ="<<low.Count()<<endl;
 

 

 

                             }
 

                            if(p.get_prior()==1)
                             {
                             medium.enQueue(p);
                            cout<<"the no of element in medium="<<medium.Count()<<endl;
 
                             }
                               if(p.get_prior()==2)
                             {
                             high.enQueue(p);
                            cout<<"the no of element in high="<<high.Count()<<endl;
 
                             }
 

 
                       }
 

                             getch();
 

 

 
                      }
 

 
mani
Questionimplemntinig priority QuesuesmemberMember 331791728 Aug '08 - 7:35 
NewsFast Priority Queue Implementation of Dijkstra Shortest Path AlgorithmmemberTolga Birdal31 Mar '08 - 5:38 
Questionremove methodmemberbelal_haija22 Mar '08 - 15:41 
Questionhashtablememberwarnockm20 Nov '07 - 15:03 
GeneralCorrectionmemberDavid Krantz14 Dec '06 - 23:49 
GeneralA-Star ImplementationmemberCastorTiu22 Sep '06 - 21:02 
GeneralTake care while using multiple threadsmembernovak.pavel31 May '06 - 2:08 
QuestionDijsktra's algorithmmembervit.ruzicka26 May '06 - 5:01 
GeneralRe: Dijsktra's algorithmmemberwarnockm20 Nov '07 - 15:05 
GeneralRemove functionalitymemberbffgdggd6 Jan '06 - 3:59 
GeneralLicense for Priority Queuemembertosboy20 Dec '05 - 23:40 
Generalconfused re: updatingmembervmy1 Jun '04 - 16:23 
GeneralRe: confused re: updatingmemberBenDi3 Jun '04 - 1:34 
GeneralRe: confused re: updatingmemberjames kolpack12 Jan '06 - 6:35 
GeneralThanks!!memberM.Shoaib Khan9 Apr '04 - 19:21 
QuestionWhat is wrong with Queue?membersandeman2 Apr '04 - 9:16 
AnswerRe: What is wrong with Queue?memberBenDi2 Apr '04 - 9:36 
GeneralRe: What is wrong with Queue?memberBenDi2 Apr '04 - 9:38 
GeneralRe: What is wrong with Queue?membersandeman2 Apr '04 - 14:00 
GeneralRe: What is wrong with Queue?memberBenDi2 Apr '04 - 21:57 
GeneralYour PriorityQueue code converted to Visual BasicmemberEnigmativity30 Mar '04 - 22:51 
GeneralRe: Your PriorityQueue code converted to Visual BasicmemberBenDi31 Mar '04 - 0:14 
QuestionCare to join a &quot;all collection&quot; project ?memberJonathan de Halleux30 Mar '04 - 2:20 
AnswerRe: Care to join a &quot;all collection&quot; project ?memberJonathan de Halleux30 Mar '04 - 2:31 
GeneralRe: Care to join a &quot;all collection&quot; project ?memberBenDi30 Mar '04 - 3:16 
GeneralRe: Care to join a &quot;all collection&quot; project ?memberJonathan de Halleux30 Mar '04 - 3:27 
GeneralRe: Care to join a &quot;all collection&quot; project ?memberBenDi2 Apr '04 - 22:45 
GeneralRe: Care to join a &quot;all collection&quot; project ?memberJonathan de Halleux3 Apr '04 - 0:41 
GeneralRe: Care to join a &quot;all collection&quot; project ?memberJonathan de Halleux3 Apr '04 - 7:51 
GeneralRe: Care to join a &quot;all collection&quot; project ?memberJonathan de Halleux2 Apr '04 - 3:46 
QuestionWhich heap ?memberJonathan de Halleux29 Mar '04 - 11:15 
AnswerRe: Which heap ?memberBenDi30 Mar '04 - 2:55 
GeneralRe: Which heap ?memberJonathan de Halleux30 Mar '04 - 3:00 
GeneralRe: Which heap ?memberBenDi30 Mar '04 - 3:24 

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 29 Mar 2004
Article Copyright 2004 by BenDi
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid