The priority queue is an important data structure where each element are kept in order of priority to be able to rapidly determine the element with the highest priority.
Each element of the queue will have a value
and a priority
.
Say we want to add elements with priority 3,4,1,2
to a priority queue in this order, the resulting priority queue will be [1,2,3,4]
:
1 2 3 4 5 6 |
|
The last element is always the one with the highest priority.
To be useful a priority queue must implement at least the following operations:
push()
: add an elementpop()
: pop the element with the highest priorityempty()
: check if the queue is emptyThere are many ways to implement it. Here we show a simple toy implementation in C:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
To keep the code short and simple we use an array of fixed size for the queue and only support int
elements. Consider the code more as "pseudo-code" than a real implementation.
This is the simplest implementation, we use an array and we don't bother sorting it or keeping it sorted.
The push()
simply adds to the next empty spot in the array:
1 2 3 4 5 |
|
The pop()
must search for the highest priority element in the array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
The complexity of push()
is O(1) but pop()
is O(N).
Notice how similar this is to "selection sort".
A better way to implement a priority queue is via a sorted array.
The push()
adds the element to the array by making sure to keep the array sorted from the lowest priority to the highest.
The last element of the array will be the one with the highest prirority.
To figure out how to do this, let's consider an example:
1 2 3 4 5 6 7 8 |
|
The implementation is then:
1 2 3 4 5 6 7 8 9 10 11 |
|
This is very similar to "insertion sort", see this article for more info about sorting algorithms.
Finally pop()
simply pops the last element of the array as it is the highest:
1 2 3 4 5 6 7 8 |
|
The complexity of push()
is O(N) but pop()
is O(1).
TODO the most efficient but also the most complex way