- Each element of the priority queue has a priority associated with it.
- Elements are added to the queue as per the priority.
- Lowest priority elements are removed first.
We can design a priority queue using two approaches in the first case we can add the queue element at the end of the queue and we can remove the elements of the queue depending on the priority. In the second case, we can add elements to the queue according to the priority and remove them from the front of the queue. In this article, we would use the second approach to implement a Priority Queue.
Note: Assuming a Priority queue can grow dynamically we are not considering the overflow condition.
Let’s see an example of a priority queue class:
As you can see in the example above we have defined the skeleton of PriorityQueue class. We have used a user defined class QElement having two property elements and priority. We have used an array in PriorityQueue class to implement the priority queue, this array is a container of QElement.
1. enqueue() – adds an element to the queue according to its priority.
In this method, we create a qElement have property element and priority. Then we iterate over the queue to find the correct location of the qElement according to its priority and add it.
2. dequeue() – Removes an element from the priority queue
This function removes an element from the front of a queue as the highest priority element is stored at the front of the priority queue. We have used the shift method of an array to remove an element from the queue.
3. front() – returns the front element of the Priority queue
This function returns the front element of the Priority queue. We simply return the 0th element of an array to get the front of a Priority queue.
4. rear() – returns the last element of the Priority queue
This function returns the last element of the queue or lowest priority element.
Let’s declare some helper method that is quite useful while working with the Priority queue.
1. isEmpty() – Returns true if the Priority queue is empty
We have used the length property of an array to get the length and if its 0 then priority queue is empty.
2. printPQueue() – It prints the element of the queue as per the priority starting from highest to lowest
In this method, we concatenate the element property of each priority queue item into a string.
Note:- Here we consider ” 1 ” as the highest priority element, you can modify this as per the requirement.
Now Let use this Priority Queue class and its different method described above
This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.