A priority queue is a queue in which you 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. This priority queue implementation provides code to implement a priority queue using an ordered array. The time complexity of enqueue is O(n), and that of dequeue is O(1).

priority queue implementation

Table of Content


Map of priority queue implementations

Part 1 – priority queue implementation – unordered array

you are here

Part 2 – priority queue implementation – ordered 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 a priority queue is the same as adding an element in a sorted array. You can put the highest key at the end.

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, you can just remove the last element.

Java

Javascript

Python


Peek

Peek is to return the value of the highest priority element. You simply return the value of the element at the highest index.

Java

Javascript

Python


Print

Print is to print all elements in the array, starting from the index 0 to the 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
Data structures introduction PDF

What’s the difference between a sorted array and a priority queue?

A sorted array is fully sorted, in which all elements are in order. A priority queue is partially ordered, in which only the first element is either the biggest or the smallest. You can use a sorted array working as a priority queue, but it is not time-efficient.