SlideShare a Scribd company logo
Priority Queue:
Priority Queue is similar to queue where we insert an element from the back and remove
an element from front, but with a one difference that the logical order of elements in the
priority queue depends on the priority of the elements. The element with highest priority
will be moved to the front of the queue and one with lowest priority will move to the back
of the queue. Thus it is possible that when you enqueue an element at the back in the
queue, it can move to front because of its highest priority.
Example:
Let’s say we have an array of 5 elements : {4, 8, 1, 7, 3} and we have to insert all the
elements in the max-priority queue.
First as the priority queue is empty, so 4 will be inserted initially.
Now when 8 will be inserted it will moved to front as 8 is greater than 4.
While inserting 1, as it is the current minimum element in the priority queue, it will
remain in the back of priority queue.
Now 7 will be inserted between 8 and 4 as 7 is smaller than 8.
Now 3 will be inserted before 1 as it is the 2nd minimum element in the priority queue. All
the steps are represented in the diagram below:
Naïve Approach:
Suppose we have N elements and we have to insert these elements in the priority
queue. We can use list and can insert elements in O(N) time and can sort them to
maintain a priority queue in O(N logN ) time.
Efficient Approach:
We can use heaps to implement the priority queue. It will take O(log N) time to insert
and delete each element in the priority queue.
Based on heap structure, priority queue also has two types max- priority queue and min
- priority queue. Max Priority Queue is based on the structure of max heap and can
perform following operations: maximum(Arr) : It returns maximum element from the Arr.
extract_maximum (Arr) - It removes and return the maximum element from the Arr.
increase_val (Arr, i , val) - It increases the key of element stored at index i in Arr to new
value val. insert_val (Arr, val ) - It inserts the element with value val in Arr.
Implementation:
length = number of elements in Arr.
Maximum :
int maximum(int Arr[ ])
{
return Arr[ 1 ]; //as the maximum element is the root element in
the max heap.
}
Complexity: O(1)
Extract Maximum: In this operation, the maximum element will be returned and the
last element of heap will be placed at index 1 and max_heapify will be performed on
node 1 as placing last element on index 1 will violate the property of max-heap.
int extract_maximum (int Arr[ ])
{
if(length == 0)
{
cout<< “Can’t remove element as queue is empty”;
return -1;
}
int max = Arr[1];
Arr[1] = Arr[length];
length = length -1;
max_heapify(Arr, 1);
return max;
}
Complexity: O(logN).
Increase Value: In case increasing value of any node, may violate the property of
max-heap, so we will swap the parent’s value with the node’s value until we get a larger
value on parent node.
void increase_value (int Arr[ ], int i, int val)
{
if(val < Arr[ i ])
{
cout<<”New value is less than current value, can’t be inserted”
<<endl;
return;
}
Arr[ i ] = val;
while( i > 1 and Arr[ i/2 ] < Arr[ i ])
{
swap|(Arr[ i/2 ], Arr[ i ]);
i = i/2;
}
}
Complexity : O(log N).
Insert Value :
void insert_value (int Arr[ ], int val)
{
length = length + 1;
Arr[ length ] = -1; //assuming all the numbers greater than 0 are to be
inserted in queue.
increase_val (Arr, length, val);
}
Complexity: O(log N).
Example:
Initially there are 5 elements in priority queue.
Operation: Insert Value(Arr, 6)
In the diagram below, inserting another element having value 6 is violating the property
of max-priority queue, so it is swapped with its parent having value 4, thus maintaining
the max priority queue.
Operation: Extract Maximum:
In the diagram below, after removing 8 and placing 4 at node 1, violates the property of
max-priority queue. So max_heapify(Arr, 1) will be performed which will maintain the
property of max - priority queue.
As discussed above, like heaps we can use priority queues in scheduling of jobs. When
there are N jobs in queue, each having its own priority. If the job with maximum priority
will be completed first and will be removed from the queue, we can use priority queue’s
operation extract_maximum here. If at every instant we have to add a new job in the
queue, we can use insert_value operation as it will insert the element in O(log N) and
will also maintain the property of max heap.

More Related Content

What's hot

Queue as data_structure
Queue as data_structureQueue as data_structure
Queue as data_structure
eShikshak
 
Circular queue
Circular queueCircular queue
Priority queues
Priority queuesPriority queues
Priority queues
Yeela Mehroz
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
Abdelrahman Saleh
 
Functional programming 101
Functional programming 101Functional programming 101
Functional programming 101
Maneesh Chaturvedi
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
Edureka!
 
Concept of Stream API Java 1.8
Concept of Stream API Java 1.8Concept of Stream API Java 1.8
Concept of Stream API Java 1.8
InnovationM
 
Arguments Object in JavaScript
Arguments Object in JavaScriptArguments Object in JavaScript
Arguments Object in JavaScript
Ideas2IT Technologies
 
Functional programming java
Functional programming javaFunctional programming java
Functional programming java
Maneesh Chaturvedi
 
basics of queues
basics of queuesbasics of queues
basics of queues
sirmanohar
 
Heapsort quick sort
Heapsort quick sortHeapsort quick sort
Heapsort quick sort
Dr Sandeep Kumar Poonia
 
Notes DATA STRUCTURE - queue
Notes DATA STRUCTURE - queueNotes DATA STRUCTURE - queue
Notes DATA STRUCTURE - queue
Farhanum Aziera
 
Quicksort Algorithm..simply defined through animations..!!
Quicksort Algorithm..simply defined through animations..!!Quicksort Algorithm..simply defined through animations..!!
Quicksort Algorithm..simply defined through animations..!!
Mahesh Tibrewal
 
3.8 quick sort
3.8 quick sort3.8 quick sort
3.8 quick sort
Krish_ver2
 
Queue
QueueQueue
Queue
QueueQueue
Array 2
Array 2Array 2
Array 2
Abbott
 
Dsa circular queue
Dsa circular queueDsa circular queue
Dsa circular queue
zzzubair
 

What's hot (20)

Queue as data_structure
Queue as data_structureQueue as data_structure
Queue as data_structure
 
Circular queue
Circular queueCircular queue
Circular queue
 
Priority queues
Priority queuesPriority queues
Priority queues
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
 
Functional programming 101
Functional programming 101Functional programming 101
Functional programming 101
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
 
Team 6
Team 6Team 6
Team 6
 
Concept of Stream API Java 1.8
Concept of Stream API Java 1.8Concept of Stream API Java 1.8
Concept of Stream API Java 1.8
 
Arguments Object in JavaScript
Arguments Object in JavaScriptArguments Object in JavaScript
Arguments Object in JavaScript
 
Functional programming java
Functional programming javaFunctional programming java
Functional programming java
 
basics of queues
basics of queuesbasics of queues
basics of queues
 
Heapsort quick sort
Heapsort quick sortHeapsort quick sort
Heapsort quick sort
 
Notes DATA STRUCTURE - queue
Notes DATA STRUCTURE - queueNotes DATA STRUCTURE - queue
Notes DATA STRUCTURE - queue
 
Quicksort Algorithm..simply defined through animations..!!
Quicksort Algorithm..simply defined through animations..!!Quicksort Algorithm..simply defined through animations..!!
Quicksort Algorithm..simply defined through animations..!!
 
3.8 quick sort
3.8 quick sort3.8 quick sort
3.8 quick sort
 
Queue
QueueQueue
Queue
 
Queue
QueueQueue
Queue
 
Queue
QueueQueue
Queue
 
Array 2
Array 2Array 2
Array 2
 
Dsa circular queue
Dsa circular queueDsa circular queue
Dsa circular queue
 

Similar to Priorty queue

Module 2 ppt.pptx
Module 2 ppt.pptxModule 2 ppt.pptx
Module 2 ppt.pptx
SonaPathak4
 
DS UNIT2QUEUES.pptx
DS UNIT2QUEUES.pptxDS UNIT2QUEUES.pptx
DS UNIT2QUEUES.pptx
VeerannaKotagi1
 
VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptx
skilljiolms
 
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
CEN 235 4. Abstract Data Types - Queue and Stack.pdfCEN 235 4. Abstract Data Types - Queue and Stack.pdf
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
vtunali
 
هياكلبيانات
هياكلبياناتهياكلبيانات
هياكلبياناتRafal Edward
 
Bca ii dfs u-2 linklist,stack,queue
Bca ii  dfs u-2 linklist,stack,queueBca ii  dfs u-2 linklist,stack,queue
Bca ii dfs u-2 linklist,stack,queue
Rai University
 
Bsc cs ii dfs u-2 linklist,stack,queue
Bsc cs ii  dfs u-2 linklist,stack,queueBsc cs ii  dfs u-2 linklist,stack,queue
Bsc cs ii dfs u-2 linklist,stack,queue
Rai University
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queue
Rai University
 
LEC4-DS ALGO.pdf
LEC4-DS  ALGO.pdfLEC4-DS  ALGO.pdf
LEC4-DS ALGO.pdf
MuhammadUmerIhtisham
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
Apurbo Datta
 
computer notes - Priority queue
computer notes -  Priority queuecomputer notes -  Priority queue
computer notes - Priority queue
ecomputernotes
 
Data Structure Lecture 4
Data Structure Lecture 4Data Structure Lecture 4
Data Structure Lecture 4
Teksify
 
Data structure.ppt
Data structure.pptData structure.ppt
Data structure.ppt
SajalFayyaz
 
Queue
QueueQueue
My lectures circular queue
My lectures circular queueMy lectures circular queue
My lectures circular queueSenthil Kumar
 
Queues in C++
Queues in C++Queues in C++
Queues in C++
Vineeta Garg
 
Queues and Stacks
Queues and StacksQueues and Stacks
Queues and Stacks
Prof Ansari
 
queues.pptx
queues.pptxqueues.pptx
queues.pptx
Aadilhussain65
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queue
Pulkitmodi1998
 

Similar to Priorty queue (20)

Module 2 ppt.pptx
Module 2 ppt.pptxModule 2 ppt.pptx
Module 2 ppt.pptx
 
DS UNIT2QUEUES.pptx
DS UNIT2QUEUES.pptxDS UNIT2QUEUES.pptx
DS UNIT2QUEUES.pptx
 
VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptx
 
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
CEN 235 4. Abstract Data Types - Queue and Stack.pdfCEN 235 4. Abstract Data Types - Queue and Stack.pdf
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
 
هياكلبيانات
هياكلبياناتهياكلبيانات
هياكلبيانات
 
Bca ii dfs u-2 linklist,stack,queue
Bca ii  dfs u-2 linklist,stack,queueBca ii  dfs u-2 linklist,stack,queue
Bca ii dfs u-2 linklist,stack,queue
 
Bsc cs ii dfs u-2 linklist,stack,queue
Bsc cs ii  dfs u-2 linklist,stack,queueBsc cs ii  dfs u-2 linklist,stack,queue
Bsc cs ii dfs u-2 linklist,stack,queue
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queue
 
LEC4-DS ALGO.pdf
LEC4-DS  ALGO.pdfLEC4-DS  ALGO.pdf
LEC4-DS ALGO.pdf
 
Queue
QueueQueue
Queue
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
computer notes - Priority queue
computer notes -  Priority queuecomputer notes -  Priority queue
computer notes - Priority queue
 
Data Structure Lecture 4
Data Structure Lecture 4Data Structure Lecture 4
Data Structure Lecture 4
 
Data structure.ppt
Data structure.pptData structure.ppt
Data structure.ppt
 
Queue
QueueQueue
Queue
 
My lectures circular queue
My lectures circular queueMy lectures circular queue
My lectures circular queue
 
Queues in C++
Queues in C++Queues in C++
Queues in C++
 
Queues and Stacks
Queues and StacksQueues and Stacks
Queues and Stacks
 
queues.pptx
queues.pptxqueues.pptx
queues.pptx
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queue
 

Recently uploaded

Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 

Recently uploaded (20)

Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 

Priorty queue

  • 1. Priority Queue: Priority Queue is similar to queue where we insert an element from the back and remove an element from front, but with a one difference that the logical order of elements in the priority queue depends on the priority of the elements. The element with highest priority will be moved to the front of the queue and one with lowest priority will move to the back of the queue. Thus it is possible that when you enqueue an element at the back in the queue, it can move to front because of its highest priority. Example: Let’s say we have an array of 5 elements : {4, 8, 1, 7, 3} and we have to insert all the elements in the max-priority queue. First as the priority queue is empty, so 4 will be inserted initially. Now when 8 will be inserted it will moved to front as 8 is greater than 4. While inserting 1, as it is the current minimum element in the priority queue, it will remain in the back of priority queue. Now 7 will be inserted between 8 and 4 as 7 is smaller than 8. Now 3 will be inserted before 1 as it is the 2nd minimum element in the priority queue. All the steps are represented in the diagram below: Naïve Approach: Suppose we have N elements and we have to insert these elements in the priority queue. We can use list and can insert elements in O(N) time and can sort them to maintain a priority queue in O(N logN ) time.
  • 2. Efficient Approach: We can use heaps to implement the priority queue. It will take O(log N) time to insert and delete each element in the priority queue. Based on heap structure, priority queue also has two types max- priority queue and min - priority queue. Max Priority Queue is based on the structure of max heap and can perform following operations: maximum(Arr) : It returns maximum element from the Arr. extract_maximum (Arr) - It removes and return the maximum element from the Arr. increase_val (Arr, i , val) - It increases the key of element stored at index i in Arr to new value val. insert_val (Arr, val ) - It inserts the element with value val in Arr. Implementation: length = number of elements in Arr. Maximum : int maximum(int Arr[ ]) { return Arr[ 1 ]; //as the maximum element is the root element in the max heap. } Complexity: O(1) Extract Maximum: In this operation, the maximum element will be returned and the last element of heap will be placed at index 1 and max_heapify will be performed on node 1 as placing last element on index 1 will violate the property of max-heap. int extract_maximum (int Arr[ ]) { if(length == 0) { cout<< “Can’t remove element as queue is empty”; return -1; } int max = Arr[1]; Arr[1] = Arr[length]; length = length -1; max_heapify(Arr, 1); return max; } Complexity: O(logN).
  • 3. Increase Value: In case increasing value of any node, may violate the property of max-heap, so we will swap the parent’s value with the node’s value until we get a larger value on parent node. void increase_value (int Arr[ ], int i, int val) { if(val < Arr[ i ]) { cout<<”New value is less than current value, can’t be inserted” <<endl; return; } Arr[ i ] = val; while( i > 1 and Arr[ i/2 ] < Arr[ i ]) { swap|(Arr[ i/2 ], Arr[ i ]); i = i/2; } } Complexity : O(log N). Insert Value : void insert_value (int Arr[ ], int val) { length = length + 1; Arr[ length ] = -1; //assuming all the numbers greater than 0 are to be inserted in queue. increase_val (Arr, length, val); } Complexity: O(log N). Example: Initially there are 5 elements in priority queue. Operation: Insert Value(Arr, 6) In the diagram below, inserting another element having value 6 is violating the property of max-priority queue, so it is swapped with its parent having value 4, thus maintaining the max priority queue.
  • 4. Operation: Extract Maximum: In the diagram below, after removing 8 and placing 4 at node 1, violates the property of max-priority queue. So max_heapify(Arr, 1) will be performed which will maintain the property of max - priority queue. As discussed above, like heaps we can use priority queues in scheduling of jobs. When there are N jobs in queue, each having its own priority. If the job with maximum priority will be completed first and will be removed from the queue, we can use priority queue’s operation extract_maximum here. If at every instant we have to add a new job in the queue, we can use insert_value operation as it will insert the element in O(log N) and will also maintain the property of max heap.