Implement priority queue using an array

A priority queue is a queue in which you insert an element at the back (enqueue) and remove an element from the front (dequeue). Meanwhile, a priority queue is a special queue, the element with the highest priority shall be dequeued first. You can implement a priority queue using an array.

priority queue diagram

Table of Content


Enqueue

To implement a priority queue, you declare an array first. To enqueue an element is the same as adding an element in a regular array -add the element at the next available spot in the array (at the back). The time complexity is O(1).

Java

Javascript

Python


Dequeue

The dequeue operation is to remove the element with the highest priority (i.e. the biggest value) from the array. Since the array is not ordered, you have to find the element with the max value first. This requires you to examine all elements in the array. When you find it, move the last element in the array to replace the biggest element, and reduce the array length. The time complexity is O(n).

Java

Javascript

Python


Peek

Peek is to return the value of the element with the highest priority. The same as dequeue, you have to find the element with the biggest value by checking all elements in the array.

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 PriorityQueueArray2.java
Download PriorityQueueArray2.js
Download PriorityQueueArray2.py

Comments are closed