A priority queue is a queue in which we insert an element at the back (enqueue) and remove an element from the front (dequeue). In addition, every element has a priority associated with it. The element with the highest priority shall be dequeued first. The Priority queue can be implemented with array or heap.

There are two ways to implement with array. The first is to implement as an ordered array. All element are ordered when insert. To dequeue, remove the last element which has the highest priority. The second way is to allow new element to enter in an arbitrary order. To dequeue, find the highest priority element by checking all elements and remove it. This post is using the second approach. For the first approach, check out implement priority queue with order array.

Table of Content


Enqueue

To enqueue an element is the same as adding an element in a regular array -add the element at next available spot in the array (ie at the end).

Java

Javascript

Python

Doodle

priority queue unordered array


Dequeue

The dequeue operation is to remove the highest priority element from the array. Since the array is not ordered, we have to find the highest priority element first. This requires to exam all elements in the array. Then move the last element in the array to this spot to replace (remove) it. This time complexity is O(n).

Java

Javascript

Python


Peek

Peek is to return the value of the highest priority element. The same as dequeue, we have to find the highest priority element by examing all elements in the array.

Java

Javascript

Python


Print

Print is to print all elements in the array, starting from the index 0 to highest index. A for loop is used to iterate through each element.

Java

Javascript

Python

Download Java, JavaScript and Python code
Priority queue (part 1) – ordered array implementation
Priority queue animated visual
Data structures and Java collections