Priority queue implementation provides code to implement priority queue using an ordered array. 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.

What is time complexity of priority queue implementation using array?

pq ordered array

There are two ways to implement priority queue 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 time complexity in enqueue is O(n), dequeue is O(1).

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. The time complexity in enqueue is O(1), dequeue is O(n).

Table of Content


Map of priority queue implementations

you are here

Part 1 – priority queue implementation – ordered array
Part 2 – priority queue implementation – unordered array
Part 3 – priority queue implementation with heap – iterative solution
Part 4 – priority queue implementation with heap – recursive solution


Enqueue

To enqueue an element in priority queue is the same as adding an element in a sorted array. If it is a descending priority (ie the bigger the key, the higher the priority), you can put the highest key at the end. If it is a ascending priority (ie the lower the key, the higher the priority), you put the lowest key at the end. In this implementation, we are applying descending priority.

Java

Javascript

Python

Doodle

priority queue ordered array


Dequeue

The dequeue operation is to remove the highest priority element from the array. Since the array is already sorted, we can just remove the last element.

Java

Javascript

Python


Peek

Peek is to return the value of the highest priority element. The same as dequeue, we simply return the value of the element at highest index.

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


Free download

Download priority queue implementation using ordered array in Java, JavaScript and Python
Download aggregate Data Structures implementations in Java
Download aggregate Data Structures implementations in JavaScript
Download aggregate Data Structures implementations in Python