Priority Queue using Binary Heap

29 Oct, 2021
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.
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.
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.
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.
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.
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 insert 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 11. 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 11 is less than node 32 so, swap node 11 and node 32. Then, swap node 14 and node 32. And at last, swap node 31 and node 32.  
ExtractMax: 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 11. But this violates the heap property, so move the replaced node down. For that, use shift down operation.  
ShiftDown operation: Swap the incorrectly placed node with a larger child until the heap property is satisfied. For Example: Node 11 is swapped with node 32 then, with node 31 and in last it is swapped with node 14.  
ChangePriority: 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 getMax.
GetMax: The max value is stored at the root of the tree. To getmax, just return the value at the root of the tree.
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: 
C++
Java
Python3
C#
Javascript
// C++ code to implement priority-queue// using array implementation of// binary heap #include <bits/stdc++.h>using namespace std; int H[50];int size = -1; // Function to return the index of the// parent node of a given nodeint parent(int i){     return (i - 1) / 2;} // Function to return the index of the// left child of the given nodeint leftChild(int i){     return ((2 * i) + 1);} // Function to return the index of the// right child of the given nodeint rightChild(int i){     return ((2 * i) + 2);} // Function to shift up the node in order// to maintain the heap propertyvoid shiftUp(int i){    while (i > 0 && H[parent(i)] < H[i]) {         // Swap parent and current node        swap(H[parent(i)], H[i]);         // Update i to parent of i        i = parent(i);    }} // Function to shift down the node in// order to maintain the heap propertyvoid shiftDown(int i){    int maxIndex = i;     // Left Child    int l = leftChild(i);     if (l <= size && H[l] > H[maxIndex]) {        maxIndex = l;    }     // Right Child    int r = rightChild(i);     if (r <= size && H[r] > H[maxIndex]) {        maxIndex = r;    }     // If i not same as maxIndex    if (i != maxIndex) {        swap(H[i], H[maxIndex]);        shiftDown(maxIndex);    }} // Function to insert a new element// in the Binary Heapvoid insert(int p){    size = size + 1;    H[size] = p;     // Shift Up to maintain heap property    shiftUp(size);} // Function to extract the element with// maximum priorityint extractMax(){    int result = H[0];     // Replace the value at the root    // with the last leaf    H[0] = H[size];    size = size - 1;     // Shift down the replaced element    // to maintain the heap property    shiftDown(0);    return result;} // Function to change the priority// of an elementvoid changePriority(int i, int p){    int oldp = H[i];    H[i] = p;     if (p > oldp) {        shiftUp(i);    }    else {        shiftDown(i);    }} // Function to get value of the current// maximum elementint getMax(){     return H[0];} // Function to remove the element// located at given indexvoid remove(int i){    H[i] = getMax() + 1;     // Shift the node to the root    // of the heap    shiftUp(i);     // Extract the node    extractMax();} // Driver Codeint 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    insert(45);    insert(20);    insert(14);    insert(12);    insert(31);    insert(7);    insert(11);    insert(13);    insert(7);     int i = 0;     // Priority queue before extracting max    cout << "Priority Queue : ";    while (i <= size) {        cout << H[i] << " ";        i++;    }     cout << "\n";     // Node with maximum priority    cout << "Node with maximum priority : "         << extractMax() << "\n";     // Priority queue after extracting max    cout << "Priority queue after "         << "extracting maximum : ";    int j = 0;    while (j <= size) {        cout << H[j] << " ";        j++;    }     cout << "\n";     // Change the priority of element    // present at index 2 to 49    changePriority(2, 49);    cout << "Priority queue after "         << "priority change : ";    int k = 0;    while (k <= size) {        cout << H[k] << " ";        k++;    }     cout << "\n";     // Remove element at index 3    remove(3);    cout << "Priority queue after "         << "removing the element : ";    int l = 0;    while (l <= size) {        cout << H[l] << " ";        l++;    }    return 0;}
// Java code to implement// priority-queue using// array implementation of// binary heapimport java.util.*;class GFG{ static int []H = new int[50];static int size = -1; // Function to return the index of the// parent node of a given nodestatic int parent(int i){  return (i - 1) / 2;} // Function to return the index of the// left child of the given nodestatic int leftChild(int i){  return ((2 * i) + 1);} // Function to return the index of the// right child of the given nodestatic int rightChild(int i){  return ((2 * i) + 2);} // Function to shift up the// node in order to maintain// the heap propertystatic void shiftUp(int i){  while (i > 0 &&         H[parent(i)] < H[i])  {    // Swap parent and current node    swap(parent(i), i);     // Update i to parent of i    i = parent(i);  }} // Function to shift down the node in// order to maintain the heap propertystatic void shiftDown(int i){  int maxIndex = i;   // Left Child  int l = leftChild(i);   if (l <= size &&      H[l] > H[maxIndex])  {    maxIndex = l;  }   // Right Child  int r = rightChild(i);   if (r <= size &&      H[r] > H[maxIndex])  {    maxIndex = r;  }   // If i not same as maxIndex  if (i != maxIndex)  {    swap(i, maxIndex);    shiftDown(maxIndex);  }} // Function to insert a// new element in// the Binary Heapstatic void insert(int p){  size = size + 1;  H[size] = p;   // Shift Up to maintain  // heap property  shiftUp(size);} // Function to extract// the element with// maximum prioritystatic int extractMax(){  int result = H[0];   // Replace the value  // at the root with  // the last leaf  H[0] = H[size];  size = size - 1;   // Shift down the replaced  // element to maintain the  // heap property  shiftDown(0);  return result;} // Function to change the priority// of an elementstatic void changePriority(int i,                           int p){  int oldp = H[i];  H[i] = p;   if (p > oldp)  {    shiftUp(i);  }  else  {    shiftDown(i);  }} // Function to get value of// the current maximum elementstatic int getMax(){  return H[0];} // Function to remove the element// located at given indexstatic void remove(int i){  H[i] = getMax() + 1;   // Shift the node to the root  // of the heap  shiftUp(i);   // Extract the node  extractMax();}   static void swap(int i, int j){  int temp= H[i];  H[i] = H[j];  H[j] = temp;} // Driver Codepublic 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  insert(45);  insert(20);  insert(14);  insert(12);  insert(31);  insert(7);  insert(11);  insert(13);  insert(7);   int i = 0;   // Priority queue before extracting max  System.out.print("Priority Queue : ");  while (i <= size)  {    System.out.print(H[i] + " ");    i++;  }   System.out.print("\n");   // Node with maximum priority  System.out.print("Node with maximum priority : " +                    extractMax() + "\n");   // Priority queue after extracting max  System.out.print("Priority queue after " +                   "extracting maximum : ");  int j = 0;  while (j <= size)  {    System.out.print(H[j] + " ");    j++;  }   System.out.print("\n");   // Change the priority of element  // present at index 2 to 49  changePriority(2, 49);  System.out.print("Priority queue after " +                   "priority change : ");  int k = 0;  while (k <= size)  {    System.out.print(H[k] + " ");    k++;  }   System.out.print("\n");   // Remove element at index 3  remove(3);  System.out.print("Priority queue after " +                   "removing the element : ");  int l = 0;  while (l <= size)  {    System.out.print(H[l] + " ");    l++;  }}} // This code is contributed by 29AjayKumar
# Python3 code to implement priority-queue# using array implementation of# binary heap H = [0]*50size = -1   # Function to return the index of the# parent node of a given nodedef parent(i) :     return (i - 1) // 2   # Function to return the index of the# left child of the given nodedef leftChild(i) :     return ((2 * i) + 1)   # Function to return the index of the# right child of the given nodedef rightChild(i) :     return ((2 * i) + 2)     # Function to shift up the # node in order to maintain # the heap propertydef shiftUp(i) :     while (i > 0 and H[parent(i)] < H[i]) :                   # Swap parent and current node        swap(parent(i), i)               # Update i to parent of i        i = parent(i)         # Function to shift down the node in# order to maintain the heap propertydef shiftDown(i) :     maxIndex = i           # Left Child    l = leftChild(i)           if (l <= size and H[l] > H[maxIndex]) :             maxIndex = l           # Right Child    r = rightChild(i)           if (r <= size and H[r] > H[maxIndex]) :             maxIndex = r           # If i not same as maxIndex    if (i != maxIndex) :             swap(i, maxIndex)        shiftDown(maxIndex)         # Function to insert a # new element in # the Binary Heapdef insert(p) :         global size    size = size + 1    H[size] = p           # Shift Up to maintain     # heap property    shiftUp(size)   # Function to extract # the element with# maximum prioritydef extractMax() :         global size    result = H[0]           # Replace the value     # at the root with     # the last leaf    H[0] = H[size]    size = size - 1           # Shift down the replaced     # element to maintain the     # heap property    shiftDown(0)    return result   # Function to change the priority# of an elementdef changePriority(i,p) :     oldp = H[i]    H[i] = p           if (p > oldp) :             shiftUp(i)      else :             shiftDown(i)   # Function to get value of # the current maximum elementdef getMax() :      return H[0]   # Function to remove the element# located at given indexdef Remove(i) :     H[i] = getMax() + 1           # Shift the node to the root    # of the heap    shiftUp(i)           # Extract the node    extractMax()   def swap(i, j) :         temp = H[i]    H[i] = H[j]    H[j] = temp     # Insert the element to the# priority queueinsert(45)insert(20)insert(14)insert(12)insert(31)insert(7)insert(11)insert(13)insert(7)   i = 0   # Priority queue before extracting maxprint("Priority Queue : ", end = "")while (i <= size) :     print(H[i], end = " ")    i += 1   print()   # Node with maximum priorityprint("Node with maximum priority :" ,  extractMax())   # Priority queue after extracting maxprint("Priority queue after extracting maximum : ", end = "")j = 0while (j <= size) :     print(H[j], end = " ")    j += 1   print()   # Change the priority of element# present at index 2 to 49changePriority(2, 49)print("Priority queue after priority change : ", end = "")k = 0while (k <= size) :     print(H[k], end = " ")    k += 1   print()   # Remove element at index 3Remove(3)print("Priority queue after removing the element : ", end = "")l = 0while (l <= size) :     print(H[l], end = " ")    l += 1         # This code is contributed by divyeshrabadiya07.
// C# code to implement priority-queue// using array implementation of// binary heapusing System; class GFG{ static int []H = new int[50];static int size = -1; // Function to return the index of the// parent node of a given nodestatic int parent(int i){    return (i - 1) / 2;} // Function to return the index of the// left child of the given nodestatic int leftChild(int i){    return ((2 * i) + 1);} // Function to return the index of the// right child of the given nodestatic int rightChild(int i){    return ((2 * i) + 2);} // Function to shift up the// node in order to maintain// the heap propertystatic void shiftUp(int i){    while (i > 0 &&           H[parent(i)] < H[i])    {                 // Swap parent and current node        swap(parent(i), i);             // Update i to parent of i        i = parent(i);    }} // Function to shift down the node in// order to maintain the heap propertystatic void shiftDown(int i){    int maxIndex = i;         // Left Child    int l = leftChild(i);         if (l <= size &&        H[l] > H[maxIndex])    {        maxIndex = l;    }         // Right Child    int r = rightChild(i);         if (r <= size &&        H[r] > H[maxIndex])    {        maxIndex = r;    }         // If i not same as maxIndex    if (i != maxIndex)    {        swap(i, maxIndex);        shiftDown(maxIndex);    }} // Function to insert a// new element in// the Binary Heapstatic void insert(int p){    size = size + 1;    H[size] = p;         // Shift Up to maintain    // heap property    shiftUp(size);} // Function to extract// the element with// maximum prioritystatic int extractMax(){    int result = H[0];         // Replace the value    // at the root with    // the last leaf    H[0] = H[size];    size = size - 1;         // Shift down the replaced    // element to maintain the    // heap property    shiftDown(0);    return result;} // Function to change the priority// of an elementstatic void changePriority(int i,                           int p){    int oldp = H[i];    H[i] = p;         if (p > oldp)    {        shiftUp(i);    }    else    {        shiftDown(i);    }} // Function to get value of// the current maximum elementstatic int getMax(){    return H[0];} // Function to remove the element// located at given indexstatic void Remove(int i){    H[i] = getMax() + 1;         // Shift the node to the root    // of the heap    shiftUp(i);         // Extract the node    extractMax();} static void swap(int i, int j){    int temp = H[i];    H[i] = H[j];    H[j] = temp;} // Driver Codepublic 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    insert(45);    insert(20);    insert(14);    insert(12);    insert(31);    insert(7);    insert(11);    insert(13);    insert(7);         int i = 0;         // Priority queue before extracting max    Console.Write("Priority Queue : ");    while (i <= size)    {        Console.Write(H[i] + " ");        i++;    }         Console.Write("\n");         // Node with maximum priority    Console.Write("Node with maximum priority : " +                   extractMax() + "\n");         // Priority queue after extracting max    Console.Write("Priority queue after " +                  "extracting maximum : ");    int j = 0;    while (j <= size)    {        Console.Write(H[j] + " ");        j++;    }         Console.Write("\n");         // Change the priority of element    // present at index 2 to 49    changePriority(2, 49);    Console.Write("Priority queue after " +                  "priority change : ");    int k = 0;    while (k <= size)    {        Console.Write(H[k] + " ");        k++;    }         Console.Write("\n");         // Remove element at index 3    Remove(3);    Console.Write("Priority queue after " +                  "removing the element : ");    int l = 0;    while (l <= size)    {        Console.Write(H[l] + " ");        l++;    }}} // This code is contributed by Amit Katiyar
<script> // Javascript code to implement priority-queue// using array implementation of// binary heap var H = Array(50).fill(0);var size = -1; // Function to return the index of the// parent node of a given nodefunction parent(i){     return parseInt((i - 1) / 2);} // Function to return the index of the// left child of the given nodefunction leftChild(i){     return parseInt((2 * i) + 1);} // Function to return the index of the// right child of the given nodefunction rightChild(i){     return parseInt((2 * i) + 2);} // Function to shift up the node in order// to maintain the heap propertyfunction shiftUp( i){    while (i > 0 && H[parent(i)] < H[i]) {         // Swap parent and current node        swap(parent(i), i);         // Update i to parent of i        i = parent(i);    }} function swap(i, j){    var temp = H[i];    H[i] = H[j];    H[j] = temp;} // Function to shift down the node in// order to maintain the heap propertyfunction shiftDown( i){    var maxIndex = i;     // Left Child    var l = leftChild(i);     if (l <= size && H[l] > H[maxIndex]) {        maxIndex = l;    }     // Right Child    var r = rightChild(i);     if (r <= size && H[r] > H[maxIndex]) {        maxIndex = r;    }     // If i not same as maxIndex    if (i != maxIndex) {        swap(i, maxIndex);        shiftDown(maxIndex);    }} // Function to insert a new element// in the Binary Heapfunction insert( p){    size = size + 1;    H[size] = p;     // Shift Up to maintain heap property    shiftUp(size);} // Function to extract the element with// maximum priorityfunction extractMax(){    var result = H[0];     // Replace the value at the root    // with the last leaf    H[0] = H[size];    size = size - 1;     // Shift down the replaced element    // to maintain the heap property    shiftDown(0);    return result;} // Function to change the priority// of an elementfunction changePriority(i, p){    var oldp = H[i];    H[i] = p;     if (p > oldp) {        shiftUp(i);    }    else {        shiftDown(i);    }} // Function to get value of the current// maximum elementfunction getMax(){     return H[0];} // Function to remove the element// located at given indexfunction remove(i){    H[i] = getMax() + 1;     // Shift the node to the root    // of the heap    shiftUp(i);     // Extract the node    extractMax();} // Driver Code/*         45        /      \       31      14      /  \    /  \     13  20  7   11    /  \   12   7Create a priority queue shown inexample in a binary max heap form.Queue will be represented in theform of array as:45 31 14 13 20 7 11 12 7 */// Insert the element to the// priority queueinsert(45);insert(20);insert(14);insert(12);insert(31);insert(7);insert(11);insert(13);insert(7);var i = 0;// Priority queue before extracting maxdocument.write( "Priority Queue : ");while (i <= size) {    document.write( H[i] + " ");    i++;}document.write( "<br>");// Node with maximum prioritydocument.write( "Node with maximum priority : "     + extractMax() + "<br>");// Priority queue after extracting maxdocument.write( "Priority queue after "     + "extracting maximum : ");var j = 0;while (j <= size) {    document.write( H[j] + " ");    j++;}document.write( "<br>"); // Change the priority of element// present at index 2 to 49changePriority(2, 49);document.write( "Priority queue after "     + "priority change : ");var k = 0;while (k <= size) {    document.write( H[k] + " ");    k++;}document.write( "<br>"); // Remove element at index 3remove(3);document.write( "Priority queue after "     + "removing the element : ");var l = 0;while (l <= size) {    document.write( H[l] + " ");    l++;} // This code is contributed by noob2000.</script>
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 
Priority queue after removing the element : 49 20 31 12 7 7 11
 
Time Complexity: The time complexity of all the operation is O(log N) except for GetMax() which has time complexity of O(1). Auxiliary Space: O(N) 
29AjayKumar
amit143katiyar
divyeshrabadiya07
noob2000
cpp-priority-queue
Data Structures-Heap
min-heap
priority-queue
Arrays
Data Structures
Heap
Data Structures
Arrays
Heap
priority-queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.