Priority Queue Using Array
Last Updated :
23 Jul, 2025
A priority queue is a data structure that stores elements with associated priorities. In a priority queue, elements are dequeued in order of their priority, with the highest priority elements being removed first. It is commonly used in algorithms like Dijkstra's for shortest path and in real-time scheduling tasks. Priority queues can be implemented using arrays, heaps, or linked lists.
Examples:
Input: Values = 4 (priority = 1), 5 (priority = 2), 6 (priority = 3), 7 (priority = 0)
Output: 7 4 5 6 (In descending order of priority, starting from the highest priority).
Explanation: The elements are stored in an array sorted by priority.
When you perform a dequeue()
, the highest priority element (7 with priority 0) is removed first.
The next highest priority element (4 with priority 1) is then at the front of the array, followed by the others.
Input: Values = 10 (priority = 3), 3 (priority = 1), 8 (priority = 2), 1 (priority = 0)
Output: 1 3 8 10 (In descending order of priority)
Explanation: The array will be sorted by priority: 1 (highest priority) comes first, followed by 3, 8, and 10. After calling dequeue()
, the element with the highest priority, 1, is removed first, then 3, followed by 8, and finally 10.
Priority Queue using Array
A priority queue stores elements where each element has a priority associated with it. In an array-based priority queue, elements are ordered so that the highest priority element is always at the front of the array. The array is sorted according to the priority values, with the element with the lowest priority value (highest priority) placed at the front.
Operations:
1. enqueue(value, priority): This function inserts a new element into the queue by adding it to the end of the array. The element is appended without any sorting. The queue remains unsorted until the peek()
or dequeue()
function is called, which scans the entire array to find and handle the element with the highest priority based on the lowest priority value.
2. dequeue(): This function removes and returns the element with the highest priority (i.e., the element with the lowest priority value). It locates the element with the highest priority using the peek()
function, then removes it by shifting the remaining elements.
3. peek(): This function returns the element with the highest priority (the element with the smallest priority value) without removing it from the queue. It scans the array to find the element with the lowest priority value and returns its index.
C++
#include <bits/stdc++.h>
using namespace std;
struct Item {
int val, priority;
};
// To store priority queue items
vector<Item> pq;
// Function to insert element in priority queue
void enqueue(int val, int priority) {
pq.push_back({val, priority});
}
// Function to get index of element with
// highest priority
int peek() {
int ind = -1, maxPriority = INT_MIN;
for (int i = 0; i < pq.size(); i++) {
// Update index if a higher priority
// is found
if (pq[i].priority > maxPriority ||
(pq[i].priority == maxPriority && pq[i].val > pq[ind].val)) {
maxPriority = pq[i].priority;
ind = i;
}
}
return ind;
}
// Function to remove the element with highest priority
void dequeue() {
int ind = peek(); // Get index of highest priority element
if (ind != -1) pq.erase(pq.begin() + ind);
}
int main() {
enqueue(10, 2);
enqueue(14, 4);
enqueue(16, 4);
enqueue(12, 3);
cout << pq[peek()].val << endl;
dequeue();
cout << pq[peek()].val << endl;
dequeue();
cout << pq[peek()].val << endl;
return 0;
}
C
#include <stdio.h>
#include <limits.h>
struct item {
int value, priority;
};
struct item pr[100000];
int size = -1;
// Function to insert element in priority queue
void enqueue(int value, int priority) {
pr[++size] = (struct item){value, priority};
}
// Function to get index of element with highest priority
int peek() {
int highestPriority = INT_MIN, ind = -1;
for (int i = 0; i <= size; i++) {
if (pr[i].priority > highestPriority ||
(pr[i].priority == highestPriority && pr[i].value > pr[ind].value)) {
highestPriority = pr[i].priority;
ind = i;
}
}
return ind;
}
// Function to remove the element with highest priority
void dequeue() {
int ind = peek();
for (int i = ind; i < size; i++) {
pr[i] = pr[i + 1];
}
size--;
}
int main() {
enqueue(10, 2);
enqueue(14, 4);
enqueue(16, 4);
enqueue(12, 3);
printf("%d\n", pr[peek()].value);
dequeue();
printf("%d\n", pr[peek()].value);
dequeue();
printf("%d\n", pr[peek()].value);
return 0;
}
Java
class Item {
int val, priority;
Item(int val, int priority) {
this.val = val;
this.priority = priority;
}
}
class PriorityQueue {
Item[] pq;
int size;
PriorityQueue(int capacity) {
pq = new Item[capacity];
size = 0;
}
// Function to insert element in priority queue
void enqueue(int val, int priority) {
pq[size++] = new Item(val, priority);
}
// Function to get index of element with highest priority
int peek() {
int ind = -1, maxPriority = Integer.MIN_VALUE;
for (int i = 0; i < size; i++) {
// Update index if a higher priority is found
if (pq[i].priority > maxPriority ||
(pq[i].priority == maxPriority && pq[i].val > pq[ind].val)) {
maxPriority = pq[i].priority;
ind = i;
}
}
return ind;
}
// Function to remove the element with highest priority
void dequeue() {
// Get index of highest priority element
int ind = peek();
if (ind != -1) {
pq[ind] = pq[size - 1];
size--;
}
}
public static void main(String[] args) {
PriorityQueue pq = new PriorityQueue(10);
pq.enqueue(10, 2);
pq.enqueue(14, 4);
pq.enqueue(16, 4);
pq.enqueue(12, 3);
System.out.println(pq.pq[pq.peek()].val);
pq.dequeue();
System.out.println(pq.pq[pq.peek()].val);
pq.dequeue();
System.out.println(pq.pq[pq.peek()].val);
}
}
Python
class Item:
def __init__(self, val, priority):
self.val = val
self.priority = priority
# To store priority queue items
pq = []
# Function to insert element in priority queue
def enqueue(val, priority):
pq.append(Item(val, priority))
# Function to get index of element with
# highest priority
def peek():
ind = -1
maxPriority = float('-inf')
for i in range(len(pq)):
# Update index if a higher priority
# is found
if pq[i].priority > maxPriority or (
pq[i].priority == maxPriority and pq[i].val > pq[ind].val):
maxPriority = pq[i].priority
ind = i
return ind
# Function to remove the element with highest priority
def dequeue():
# Get index of highest priority element
ind = peek()
if ind != -1:
pq.pop(ind)
if __name__ == '__main__':
enqueue(10, 2)
enqueue(14, 4)
enqueue(16, 4)
enqueue(12, 3)
print(pq[peek()].val)
dequeue()
print(pq[peek()].val)
dequeue()
print(pq[peek()].val)
C#
using System;
using System.Collections.Generic;
class Item {
public int val, priority;
public Item(int val, int priority) {
this.val = val;
this.priority = priority;
}
}
// To store priority queue items
List<Item> pq = new List<Item>();
// Function to insert element in priority queue
void enqueue(int val, int priority) {
pq.Add(new Item(val, priority));
}
// Function to get index of element with
// highest priority
int peek() {
int ind = -1;
int maxPriority = int.MinValue;
for (int i = 0; i < pq.Count; i++) {
// Update index if a higher priority
// is found
if (pq[i].priority > maxPriority ||
(pq[i].priority == maxPriority && pq[i].val > pq[ind].val)) {
maxPriority = pq[i].priority;
ind = i;
}
}
return ind;
}
// Function to remove the element with highest priority
void dequeue() {
// Get index of highest priority element
int ind = peek();
if (ind != -1) pq.RemoveAt(ind);
}
class GfG {
static void Main() {
enqueue(10, 2);
enqueue(14, 4);
enqueue(16, 4);
enqueue(12, 3);
Console.WriteLine(pq[peek()].val);
dequeue();
Console.WriteLine(pq[peek()].val);
dequeue();
Console.WriteLine(pq[peek()].val);
}
}
JavaScript
class Item {
constructor(val, priority) {
this.val = val;
this.priority = priority;
}
}
// To store priority queue items
let pq = [];
// Function to insert element in priority queue
function enqueue(val, priority) {
pq.push(new Item(val, priority));
}
// Function to get index of element with
// highest priority
function peek() {
let ind = -1;
let maxPriority = Number.NEGATIVE_INFINITY;
for (let i = 0; i < pq.length; i++) {
// Update index if a higher priority
// is found
if (pq[i].priority > maxPriority ||
(pq[i].priority === maxPriority && pq[i].val > pq[ind].val)) {
maxPriority = pq[i].priority;
ind = i;
}
}
return ind;
}
// Function to remove the element with highest priority
function dequeue() {
// Get index of highest priority element
let ind = peek();
if (ind !== -1) pq.splice(ind, 1);
}
enqueue(10, 2);
enqueue(14, 4);
enqueue(16, 4);
enqueue(12, 3);
console.log(pq[peek()].val);
dequeue();
console.log(pq[peek()].val);
dequeue();
console.log(pq[peek()].val);
Time Complexity:
enqueue(value, priority)
: O(1) (since it's just an insertion).peek()
: O(n) (iterating through the entire array).dequeue()
: O(n) (finding the highest-priority element and shifting elements).
Auxiliary Space: The auxiliary space complexity for this program is O(1)
Related Articles:
What is Priority Queue | Introduction to Priority Queue
Priority Queue using Linked List
Priority Queue using Binary Heap
Why is Binary Heap Preferred over BST for Priority Queue ?
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem