Priority Queue using Binary Heap
What is a Priority Queue ?
Priority Queue is an extension of the queue with the following properties:
- Every item has a priority associated with it.
- An element with high priority is dequeued before an element with low priority.
- If two elements have the same priority, they are served according to their order in the queue.
What is a Binary Heap ?
A Binary Heap is a Binary Tree with the following properties:
- It is a Complete Tree. This property of Binary Heap makes them suitable to be stored in an array.
- A Binary Heap is either Min Heap or Max Heap.
- In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree.
- Similarly, in a Max Binary Heap, the key at the root must be maximum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree.
Operation on Binary Heap
- insert(p): Inserts a new element with priority p.
- extractMax(): Extracts an element with maximum priority.
- remove(i): Removes an element pointed by an iterator i.
- getMax(): Returns an element with maximum priority.
- changePriority(i, p): Changes the priority of an element pointed by i to p.
Example of A Binary Max Heap
- Suppose below is the given Binary Heap that follows all the properties of Binary Max Heap.

- Now a node with value 32 need to be inserted in the above heap: To insert an element, attach the new element to any leaf. For Example A node with priority 32 can be added to the leaf of the node 7. But this violates the heap property. To maintain the heap property, shift up the new node 32.

- Shift Up Operation get node with 32 at the correct position: Swap the incorrectly placed node with its parent until the heap property is satisfied. For Example: As node 7 is less than node 32 so, swap node 7 and node 32. Then, swap node 31 and node 32.

- Extract Max: The maximum value is stored at the root of the tree. But the root of the tree cannot be directly removed. First, it is replaced with any one of the leaves and then removed. For Example: To remove Node 45, it is first replaced with node 7. But this violates the heap property, so move the replaced node down. For that, use shift-down operation.

- Shift Down Operation: Swap the incorrectly placed node with a larger child until the heap property is satisfied. For Example Node 7 is swapped with node 32 then, last it is swapped with node 31.

- Change Priority: Let the changed element shift up or down depending on whether its priority decreased or increased. For Example: Change the priority of nodes 11 to 35, due to this change the node has to shift up the node in order to maintain the heap property.
- Remove: To remove an element, change its priority to a value larger than the current maximum, then shift it up, and then extract it using extract max. Find the current maximum using get Max.
- Get Max: The max value is stored at the root of the tree. To get max, just return the value at the root of the tree.
Array Representation of Binary Heap
Since the heap is maintained in form of a complete binary tree, because of this fact the heap can be represented in the form of an array. To keep the tree complete and shallow, while inserting a new element insert it in the leftmost vacant position in the last level i.e., at the end of our array. Similarly, while extracting maximum replace the root with the last leaf at the last level i.e., the last element of the array.
Below is the illustration of the same:

Below is the program to implement Priority Queue using Binary Heap:
#include <bits/stdc++.h>
using namespace std;
// Function to return the index of the
// parent node of a given node
int parent(int i) {
return (i - 1) / 2;
}
// Function to return the index of the
// left child of the given node
int leftChild(int i) {
return ((2 * i) + 1);
}
// Function to return the index of the
// right child of the given node
int rightChild(int i){
return ((2 * i) + 2);
}
// Function to shift up the node in order
// to maintain the heap property
void shiftUp(int i, vector<int> &arr) {
while (i > 0 && arr[parent(i)] < arr[i]) {
// Swap parent and current node
swap(arr[parent(i)], arr[i]);
// Update i to parent of i
i = parent(i);
}
}
// Function to shift down the node in
// order to maintain the heap property
void shiftDown(int i, vector<int> &arr, int &size) {
int maxIndex = i;
// Left Child
int l = leftChild(i);
if (l <= size && arr[l] > arr[maxIndex]) {
maxIndex = l;
}
// Right Child
int r = rightChild(i);
if (r <= size && arr[r] > arr[maxIndex]) {
maxIndex = r;
}
// If i not same as maxIndex
if (i != maxIndex) {
swap(arr[i], arr[maxIndex]);
shiftDown(maxIndex, arr, size);
}
}
// Function to insert a new element
// in the Binary Heap
void insert(int p, vector<int> &arr, int &size) {
size = size + 1;
arr.push_back(p);
// Shift Up to maintain heap property
shiftUp(size, arr);
}
// Function to extract the element with
// maximum priority
int extractMax(vector<int> &arr, int &size) {
int result = arr[0];
// Replace the value at the root
// with the last leaf
arr[0] = arr[size];
size = size - 1;
// Shift down the replaced element
// to maintain the heap property
shiftDown(0, arr, size);
return result;
}
// Function to change the priority
// of an element
void changePriority(int i, int p, vector<int> &arr, int &size) {
int oldp = arr[i];
arr[i] = p;
if (p > oldp) {
shiftUp(i, arr);
}
else {
shiftDown(i, arr, size);
}
}
// Function to get value of the current
// maximum element
int getMax(vector<int> &arr) {
return arr[0];
}
// Function to remove the element
// located at given index
void remove(int i, vector<int> &arr, int &size) {
arr[i] = getMax(arr) + 1;
// Shift the node to the root
// of the heap
shiftUp(i, arr);
// Extract the node
extractMax(arr, size);
}
int main() {
/* 45
/ \
31 14
/ \ / \
13 20 7 11
/ \
12 7
Create a priority queue shown in
example in a binary max heap form.
Queue will be represented in the
form of array as:
45 31 14 13 20 7 11 12 7 */
// Insert the element to the
// priority queue
vector<int> arr;
int size = -1;
insert(45, arr, size);
insert(20, arr, size);
insert(14, arr, size);
insert(12, arr, size);
insert(31, arr, size);
insert(7, arr, size);
insert(11, arr, size);
insert(13, arr, size);
insert(7, arr, size);
int i = 0;
// Priority queue before extracting max
cout << "Priority Queue : ";
while (i <= size) {
cout << arr[i] << " ";
i++;
}
cout << endl;
// Node with maximum priority
cout << "Node with maximum priority : "
<< extractMax(arr, size) << endl;
// Priority queue after extracting max
cout << "Priority queue after "
<< "extracting maximum : ";
int j = 0;
while (j <= size) {
cout << arr[j] << " ";
j++;
}
cout << endl;
// Change the priority of element
// present at index 2 to 49
changePriority(2, 49, arr, size);
cout << "Priority queue after "
<< "priority change : ";
int k = 0;
while (k <= size) {
cout << arr[k] << " ";
k++;
}
cout << endl;
// Remove element at index 3
remove(3, arr, size);
cout << "Priority queue after "
<< "removing the element : ";
int l = 0;
while (l <= size) {
cout << arr[l] << " ";
l++;
}
return 0;
}
import java.util.*;
public class GfG {
// Function to return the index of the
// parent node of a given node
public static int parent(int i) {
return (i - 1) / 2;
}
// Function to return the index of the
// left child of the given node
public static int leftChild(int i) {
return ((2 * i) + 1);
}
// Function to return the index of the
// right child of the given node
public static int rightChild(int i){
return ((2 * i) + 2);
}
// Function to shift up the node in order
// to maintain the heap property
public static void shiftUp(int i, ArrayList<Integer> arr) {
while (i > 0 && arr.get(parent(i)) < arr.get(i)) {
// Swap parent and current node
Collections.swap(arr, parent(i), i);
// Update i to parent of i
i = parent(i);
}
}
// Function to shift down the node in
// order to maintain the heap property
public static void shiftDown(int i, ArrayList<Integer> arr, int[] size) {
int maxIndex = i;
// Left Child
int l = leftChild(i);
if (l <= size[0] && arr.get(l) > arr.get(maxIndex)) {
maxIndex = l;
}
// Right Child
int r = rightChild(i);
if (r <= size[0] && arr.get(r) > arr.get(maxIndex)) {
maxIndex = r;
}
// If i not same as maxIndex
if (i != maxIndex) {
Collections.swap(arr, i, maxIndex);
shiftDown(maxIndex, arr, size);
}
}
// Function to insert a new element
// in the Binary Heap
public static void insert(int p, ArrayList<Integer> arr, int[] size) {
size[0] = size[0] + 1;
arr.add(p);
// Shift Up to maintain heap property
shiftUp(size[0], arr);
}
// Function to extract the element with
// maximum priority
public static int extractMax(ArrayList<Integer> arr, int[] size) {
int result = arr.get(0);
// Replace the value at the root
// with the last leaf
arr.set(0, arr.get(size[0]));
size[0] = size[0] - 1;
// Shift down the replaced element
// to maintain the heap property
shiftDown(0, arr, size);
return result;
}
// Function to change the priority
// of an element
public static void changePriority(int i, int p, ArrayList<Integer> arr, int[] size) {
int oldp = arr.get(i);
arr.set(i, p);
if (p > oldp) {
shiftUp(i, arr);
}
else {
shiftDown(i, arr, size);
}
}
// Function to get value of the current
// maximum element
public static int getMax(ArrayList<Integer> arr) {
return arr.get(0);
}
// Function to remove the element
// located at given index
public static void remove(int i, ArrayList<Integer> arr, int[] size) {
arr.set(i, getMax(arr) + 1);
// Shift the node to the root
// of the heap
shiftUp(i, arr);
// Extract the node
extractMax(arr, size);
}
public static void main(String[] args) {
/* 45
/ \
31 14
/ \ / \
13 20 7 11
/ \
12 7
Create a priority queue shown in
example in a binary max heap form.
Queue will be represented in the
form of array as:
45 31 14 13 20 7 11 12 7 */
// Insert the element to the
// priority queue
ArrayList<Integer> arr = new ArrayList<Integer>();
int[] size = {-1};
insert(45, arr, size);
insert(20, arr, size);
insert(14, arr, size);
insert(12, arr, size);
insert(31, arr, size);
insert(7, arr, size);
insert(11, arr, size);
insert(13, arr, size);
insert(7, arr, size);
int i = 0;
// Priority queue before extracting max
System.out.print("Priority Queue : ");
while (i <= size[0]) {
System.out.print(arr.get(i) + " ");
i++;
}
System.out.println();
// Node with maximum priority
System.out.println("Node with maximum priority : " + extractMax(arr, size));
// Priority queue after extracting max
System.out.print("Priority queue after extracting maximum : ");
int j = 0;
while (j <= size[0]) {
System.out.print(arr.get(j) + " ");
j++;
}
System.out.println();
// Change the priority of element
// present at index 2 to 49
changePriority(2, 49, arr, size);
System.out.print("Priority queue after priority change : ");
int k = 0;
while (k <= size[0]) {
System.out.print(arr.get(k) + " ");
k++;
}
System.out.println();
// Remove element at index 3
remove(3, arr, size);
System.out.print("Priority queue after removing the element : ");
int l = 0;
while (l <= size[0]) {
System.out.print(arr.get(l) + " ");
l++;
}
}
}
# Function to return the index of the
# parent node of a given node
def parent(i):
return (i - 1) // 2
# Function to return the index of the
# left child of the given node
def leftChild(i):
return ((2 * i) + 1)
# Function to return the index of the
# right child of the given node
def rightChild(i):
return ((2 * i) + 2)
# Function to shift up the node in order
# to maintain the heap property
def shiftUp(i, arr):
while i > 0 and arr[parent(i)] < arr[i]:
# Swap parent and current node
arr[parent(i)], arr[i] = arr[i], arr[parent(i)]
# Update i to parent of i
i = parent(i)
# Function to shift down the node in
# order to maintain the heap property
def shiftDown(i, arr, size):
maxIndex = i
# Left Child
l = leftChild(i)
if l <= size and arr[l] > arr[maxIndex]:
maxIndex = l
# Right Child
r = rightChild(i)
if r <= size and arr[r] > arr[maxIndex]:
maxIndex = r
# If i not same as maxIndex
if i != maxIndex:
arr[i], arr[maxIndex] = arr[maxIndex], arr[i]
shiftDown(maxIndex, arr, size)
# Function to insert a new element
# in the Binary Heap
def insert(p, arr, size):
size[0] = size[0] + 1
arr.append(p)
# Shift Up to maintain heap property
shiftUp(size[0], arr)
# Function to extract the element with
# maximum priority
def extractMax(arr, size):
result = arr[0]
# Replace the value at the root
# with the last leaf
arr[0] = arr[size[0]]
size[0] = size[0] - 1
# Shift down the replaced element
# to maintain the heap property
shiftDown(0, arr, size[0])
return result
# Function to change the priority
# of an element
def changePriority(i, p, arr, size):
oldp = arr[i]
arr[i] = p
if p > oldp:
shiftUp(i, arr)
else:
shiftDown(i, arr, size[0])
# Function to get value of the current
# maximum element
def getMax(arr):
return arr[0]
# Function to remove the element
# located at given index
def remove(i, arr, size):
arr[i] = getMax(arr) + 1
# Shift the node to the root
# of the heap
shiftUp(i, arr)
# Extract the node
extractMax(arr, size)
if __name__ == "__main__":
# 45
# / \
# 31 14
# / \ / \
# 13 20 7 11
# / \
#12 7
#Create a priority queue shown in
#example in a binary max heap form.
#Queue will be represented in the
#form of array as:
#45 31 14 13 20 7 11 12 7
# Insert the element to the
# priority queue
arr = []
size = [-1]
insert(45, arr, size)
insert(20, arr, size)
insert(14, arr, size)
insert(12, arr, size)
insert(31, arr, size)
insert(7, arr, size)
insert(11, arr, size)
insert(13, arr, size)
insert(7, arr, size)
i = 0
# Priority queue before extracting max
print("Priority Queue : ", end="")
while i <= size[0]:
print(arr[i], end=" ")
i += 1
print()
# Node with maximum priority
print("Node with maximum priority : " + str(extractMax(arr, size)))
# Priority queue after extracting max
print("Priority queue after extracting maximum : ", end="")
j = 0
while j <= size[0]:
print(arr[j], end=" ")
j += 1
print()
# Change the priority of element
# present at index 2 to 49
changePriority(2, 49, arr, size)
print("Priority queue after priority change : ", end="")
k = 0
while k <= size[0]:
print(arr[k], end=" ")
k += 1
print()
# Remove element at index 3
remove(3, arr, size)
print("Priority queue after removing the element : ", end="")
l = 0
while l <= size[0]:
print(arr[l], end=" ")
l += 1
using System;
using System.Collections.Generic;
public class GfG {
// Function to return the index of the
// parent node of a given node
public static int Parent(int i) {
return (i - 1) / 2;
}
// Function to return the index of the
// left child of the given node
public static int LeftChild(int i) {
return ((2 * i) + 1);
}
// Function to return the index of the
// right child of the given node
public static int RightChild(int i){
return ((2 * i) + 2);
}
// Function to shift up the node in order
// to maintain the heap property
public static void ShiftUp(int i, List<int> arr) {
while (i > 0 && arr[Parent(i)] < arr[i]) {
// Swap parent and current node
int temp = arr[Parent(i)];
arr[Parent(i)] = arr[i];
arr[i] = temp;
// Update i to parent of i
i = Parent(i);
}
}
// Function to shift down the node in
// order to maintain the heap property
public static void ShiftDown(int i, List<int> arr, ref int size) {
int maxIndex = i;
// Left Child
int l = LeftChild(i);
if (l <= size && arr[l] > arr[maxIndex]) {
maxIndex = l;
}
// Right Child
int r = RightChild(i);
if (r <= size && arr[r] > arr[maxIndex]) {
maxIndex = r;
}
// If i not same as maxIndex
if (i != maxIndex) {
int temp = arr[i];
arr[i] = arr[maxIndex];
arr[maxIndex] = temp;
ShiftDown(maxIndex, arr, ref size);
}
}
// Function to insert a new element
// in the Binary Heap
public static void Insert(int p, List<int> arr, ref int size) {
size = size + 1;
arr.Add(p);
// Shift Up to maintain heap property
ShiftUp(size, arr);
}
// Function to extract the element with
// maximum priority
public static int ExtractMax(List<int> arr, ref int size) {
int result = arr[0];
// Replace the value at the root
// with the last leaf
arr[0] = arr[size];
size = size - 1;
// Shift down the replaced element
// to maintain the heap property
ShiftDown(0, arr, ref size);
return result;
}
// Function to change the priority
// of an element
public static void ChangePriority(int i, int p, List<int> arr, ref int size) {
int oldp = arr[i];
arr[i] = p;
if (p > oldp) {
ShiftUp(i, arr);
}
else {
ShiftDown(i, arr, ref size);
}
}
// Function to get value of the current
// maximum element
public static int GetMax(List<int> arr) {
return arr[0];
}
// Function to remove the element
// located at given index
public static void Remove(int i, List<int> arr, ref int size) {
arr[i] = GetMax(arr) + 1;
// Shift the node to the root
// of the heap
ShiftUp(i, arr);
// Extract the node
ExtractMax(arr, ref size);
}
public static void Main(string[] args) {
/* 45
/ \
31 14
/ \ / \
13 20 7 11
/ \
12 7
Create a priority queue shown in
example in a binary max heap form.
Queue will be represented in the
form of array as:
45 31 14 13 20 7 11 12 7 */
// Insert the element to the
// priority queue
List<int> arr = new List<int>();
int size = -1;
Insert(45, arr, ref size);
Insert(20, arr, ref size);
Insert(14, arr, ref size);
Insert(12, arr, ref size);
Insert(31, arr, ref size);
Insert(7, arr, ref size);
Insert(11, arr, ref size);
Insert(13, arr, ref size);
Insert(7, arr, ref size);
int i = 0;
// Priority queue before extracting max
Console.Write("Priority Queue : ");
while (i <= size) {
Console.Write(arr[i] + " ");
i++;
}
Console.WriteLine();
// Node with maximum priority
Console.WriteLine("Node with maximum priority : " + ExtractMax(arr, ref size));
// Priority queue after extracting max
Console.Write("Priority queue after extracting maximum : ");
int j = 0;
while (j <= size) {
Console.Write(arr[j] + " ");
j++;
}
Console.WriteLine();
// Change the priority of element
// present at index 2 to 49
ChangePriority(2, 49, arr, ref size);
Console.Write("Priority queue after priority change : ");
int k = 0;
while (k <= size) {
Console.Write(arr[k] + " ");
k++;
}
Console.WriteLine();
// Remove element at index 3
Remove(3, arr, ref size);
Console.Write("Priority queue after removing the element : ");
int l = 0;
while (l <= size) {
Console.Write(arr[l] + " ");
l++;
}
}
}
// Function to return the index of the
// parent node of a given node
function parent(i) {
return Math.floor((i - 1) / 2);
}
// Function to return the index of the
// left child of the given node
function leftChild(i) {
return ((2 * i) + 1);
}
// Function to return the index of the
// right child of the given node
function rightChild(i){
return ((2 * i) + 2);
}
// Function to shift up the node in order
// to maintain the heap property
function shiftUp(i, arr) {
while (i > 0 && arr[parent(i)] < arr[i]) {
// Swap parent and current node
let temp = arr[parent(i)];
arr[parent(i)] = arr[i];
arr[i] = temp;
// Update i to parent of i
i = parent(i);
}
}
// Function to shift down the node in
// order to maintain the heap property
function shiftDown(i, arr, size) {
let maxIndex = i;
// Left Child
let l = leftChild(i);
if (l <= size && arr[l] > arr[maxIndex]) {
maxIndex = l;
}
// Right Child
let r = rightChild(i);
if (r <= size && arr[r] > arr[maxIndex]) {
maxIndex = r;
}
// If i not same as maxIndex
if (i != maxIndex) {
let temp = arr[i];
arr[i] = arr[maxIndex];
arr[maxIndex] = temp;
shiftDown(maxIndex, arr, size);
}
}
// Function to insert a new element
// in the Binary Heap
function insert(p, arr, sizeObj) {
sizeObj.size = sizeObj.size + 1;
arr.push(p);
// Shift Up to maintain heap property
shiftUp(sizeObj.size, arr);
}
// Function to extract the element with
// maximum priority
function extractMax(arr, sizeObj) {
let result = arr[0];
// Replace the value at the root
// with the last leaf
arr[0] = arr[sizeObj.size];
sizeObj.size = sizeObj.size - 1;
// Shift down the replaced element
// to maintain the heap property
shiftDown(0, arr, sizeObj.size);
return result;
}
// Function to change the priority
// of an element
function changePriority(i, p, arr, sizeObj) {
let oldp = arr[i];
arr[i] = p;
if (p > oldp) {
shiftUp(i, arr);
}
else {
shiftDown(i, arr, sizeObj.size);
}
}
// Function to get value of the current
// maximum element
function getMax(arr) {
return arr[0];
}
// Function to remove the element
// located at given index
function remove(i, arr, sizeObj) {
arr[i] = getMax(arr) + 1;
// Shift the node to the root
// of the heap
shiftUp(i, arr);
// Extract the node
extractMax(arr, sizeObj);
}
function main() {
/* 45
/ \
31 14
/ \ / \
13 20 7 11
/ \
12 7
Create a priority queue shown in
example in a binary max heap form.
Queue will be represented in the
form of array as:
45 31 14 13 20 7 11 12 7 */
// Insert the element to the
// priority queue
let arr = [];
let sizeObj = { size: -1 };
insert(45, arr, sizeObj);
insert(20, arr, sizeObj);
insert(14, arr, sizeObj);
insert(12, arr, sizeObj);
insert(31, arr, sizeObj);
insert(7, arr, sizeObj);
insert(11, arr, sizeObj);
insert(13, arr, sizeObj);
insert(7, arr, sizeObj);
let i = 0;
// Priority queue before extracting max
let output = "Priority Queue : ";
while (i <= sizeObj.size) {
output += arr[i] + " ";
i++;
}
console.log(output);
// Node with maximum priority
console.log("Node with maximum priority : " + extractMax(arr, sizeObj));
// Priority queue after extracting max
output = "Priority queue after extracting maximum : ";
let j = 0;
while (j <= sizeObj.size) {
output += arr[j] + " ";
j++;
}
console.log(output);
// Change the priority of element
// present at index 2 to 49
changePriority(2, 49, arr, sizeObj);
output = "Priority queue after priority change : ";
let k = 0;
while (k <= sizeObj.size) {
output += arr[k] + " ";
k++;
}
console.log(output);
// Remove element at index 3
remove(3, arr, sizeObj);
output = "Priority queue after removing the element : ";
let l = 0;
while (l <= sizeObj.size) {
output += arr[l] + " ";
l++;
}
console.log(output);
}
main();
Output
Priority Queue : 45 31 14 13 20 7 11 12 7 Node with maximum priority : 45 Priority queue after extracting maximum : 31 20 14 13 7 7 11 12 Priority queue after priority change : 49 20 31 13 7 7 11 12...
Time Complexity: O(log n), for all the operation, except getMax(), which has time complexity of O(1).
Space Complexity: O(n)
[Alternate Approach] – Using Generic Template in Statically Typed Languages like C++, Java and C#
Below is a valid approach to implementing a priority queue using a max heap. This implementation follows a class-based structure with a generic template, making it adaptable to all data types rather than being restricted to a specific one.
Below is given the implementation:
#include <bits/stdc++.h>
using namespace std;
// Priority queue implementation
template <typename T>
class PriorityQueue {
private:
vector<T> data;
public:
PriorityQueue() {}
// to enqueue the element
void Enqueue(T item) {
data.push_back(item);
int ci = data.size() - 1;
// Re-structure heap(Max Heap) so that after
// addition max element will lie on top of pq
while (ci > 0) {
// Parent index of current index
int pi = (ci - 1) / 2;
if (data[ci] <= data[pi])
break;
// If current index element is greater
// than parent index element then swap
T tmp = data[ci];
data[ci] = data[pi];
data[pi] = tmp;
ci = pi;
}
}
T Dequeue() {
// deleting top element of pq
int li = data.size() - 1;
T frontItem = data[0];
data[0] = data[li];
data.pop_back();
--li;
int pi = 0;
// Re-structure heap(Max Heap) so that after
// deletion max element will lie on top of pq
while (true) {
// Left child index of parent index
int ci = pi * 2 + 1;
if (ci > li)
break;
// Right child index of parent index
int rc = ci + 1;
// If right child index is less than left child
// index then assign right child index to ci
if (rc <= li && data[rc] > data[ci])
ci = rc;
if (data[pi] >= data[ci])
break;
// If parent index element is less than child
// index element then swap
T tmp = data[pi];
data[pi] = data[ci];
data[ci] = tmp;
pi = ci;
}
return frontItem;
}
// Function which returns peek element
T Peek() {
T frontItem = data[0];
return frontItem;
}
int Count() {
return data.size();
}
};
int main() {
PriorityQueue<int> pq;
cout << "Size" << " " << "Peek" << endl;
pq.Enqueue(1);
cout << pq.Count() << " " << pq.Peek() << endl;
pq.Enqueue(10);
pq.Enqueue(-8);
cout << pq.Count() << " " << pq.Peek() << endl;
pq.Dequeue();
cout << pq.Count() << " " << pq.Peek() << endl;
pq.Dequeue();
cout << pq.Count() << " " << pq.Peek() << endl;
pq.Enqueue(25);
cout << pq.Count() << " " << pq.Peek() << endl;
return 0;
}
import java.util.*;
public class GfG {
// Priority queue implementation
public static class PriorityQueue<T extends Comparable<T>> {
private ArrayList<T> data;
public PriorityQueue() {
data = new ArrayList<T>();
}
// to enqueue the element
public void Enqueue(T item) {
data.add(item);
int ci = data.size() - 1;
// Re-structure heap(Max Heap) so that after
// addition max element will lie on top of pq
while (ci > 0) {
// Parent index of current index
int pi = (ci - 1) / 2;
if (data.get(ci).compareTo(data.get(pi)) <= 0)
break;
// If current index element is greater
// than parent index element then swap
T tmp = data.get(ci);
data.set(ci, data.get(pi));
data.set(pi, tmp);
ci = pi;
}
}
public T Dequeue() {
// deleting top element of pq
int li = data.size() - 1;
T frontItem = data.get(0);
data.set(0, data.get(li));
data.remove(li);
--li;
int pi = 0;
// Re-structure heap(Max Heap) so that after
// deletion max element will lie on top of pq
while (true) {
// Left child index of parent index
int ci = pi * 2 + 1;
if (ci > li)
break;
// Right child index of parent index
int rc = ci + 1;
// If right child index is less than left child
// index then assign right child index to ci
if (rc <= li && data.get(rc).compareTo(data.get(ci)) > 0)
ci = rc;
if (data.get(pi).compareTo(data.get(ci)) >= 0)
break;
// If parent index element is less than child
// index element then swap
T tmp = data.get(pi);
data.set(pi, data.get(ci));
data.set(ci, tmp);
pi = ci;
}
return frontItem;
}
// Function which returns peek element
public T Peek() {
T frontItem = data.get(0);
return frontItem;
}
public int Count() {
return data.size();
}
}
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
System.out.println("Size" + " " + "Peek");
pq.Enqueue(1);
System.out.println(pq.Count() + " " + pq.Peek());
pq.Enqueue(10);
pq.Enqueue(-8);
System.out.println(pq.Count() + " " + pq.Peek());
pq.Dequeue();
System.out.println(pq.Count() + " " + pq.Peek());
pq.Dequeue();
System.out.println(pq.Count() + " " + pq.Peek());
pq.Enqueue(25);
System.out.println(pq.Count() + " " + pq.Peek());
}
}
using System;
using System.Collections.Generic;
public class GfG {
// Priority queue implementation
public class PriorityQueue<T> where T : IComparable<T> {
private List<T> data;
public PriorityQueue() {
data = new List<T>();
}
// to enqueue the element
public void Enqueue(T item) {
data.Add(item);
int ci = data.Count - 1;
// Re-structure heap(Max Heap) so that after
// addition max element will lie on top of pq
while (ci > 0) {
// Parent index of current index
int pi = (ci - 1) / 2;
if (data[ci].CompareTo(data[pi]) <= 0)
break;
// If current index element is greater
// than parent index element then swap
T tmp = data[ci];
data[ci] = data[pi];
data[pi] = tmp;
ci = pi;
}
}
public T Dequeue() {
// deleting top element of pq
int li = data.Count - 1;
T frontItem = data[0];
data[0] = data[li];
data.RemoveAt(li);
--li;
int pi = 0;
// Re-structure heap(Max Heap) so that after
// deletion max element will lie on top of pq
while (true) {
// Left child index of parent index
int ci = pi * 2 + 1;
if (ci > li)
break;
// Right child index of parent index
int rc = ci + 1;
// If right child index is less than left child
// index then assign right child index to ci
if (rc <= li && data[rc].CompareTo(data[ci]) > 0)
ci = rc;
if (data[pi].CompareTo(data[ci]) >= 0)
break;
// If parent index element is less than child
// index element then swap
T tmp = data[pi];
data[pi] = data[ci];
data[ci] = tmp;
pi = ci;
}
return frontItem;
}
// Function which returns peek element
public T Peek() {
T frontItem = data[0];
return frontItem;
}
public int Count() {
return data.Count;
}
}
public static void Main(string[] args) {
PriorityQueue<int> pq = new PriorityQueue<int>();
Console.WriteLine("Size" + " " + "Peek");
pq.Enqueue(1);
Console.WriteLine(pq.Count() + " " + pq.Peek());
pq.Enqueue(10);
pq.Enqueue(-8);
Console.WriteLine(pq.Count() + " " + pq.Peek());
pq.Dequeue();
Console.WriteLine(pq.Count() + " " + pq.Peek());
pq.Dequeue();
Console.WriteLine(pq.Count() + " " + pq.Peek());
pq.Enqueue(25);
Console.WriteLine(pq.Count() + " " + pq.Peek());
}
}
Output
Size Peek 1 1 3 10 2 1 1 -8 2 25
Time Complexity: O(log(n)), for enqueue operation and O(log(n)) for dequeue operation.
Space complexity: O(n), as we need n size array for implementation.