SlideShare a Scribd company logo
1 of 27
Download to read offline
Chapter 6: Priority Queues (Heaps)
Text: Read Weiss, §6.1 – 6.3
1
2
Priority Queue (Heap)
• A kind of queue
• Dequeue gets element with the highest priority
• Priority is based on a comparable value (key) of
each object (smaller value higher priority, or higher value
higher priority)
• Example Applications:
– printer -> print (dequeue) the shortest document first
– operating system -> run (dequeue) the shortest job first
– normal queue -> dequeue the first enqueued element first
3
Priority Queue (Heap) Operations
• insert (enqueue)
• deleteMin (dequeue)
– smaller value higher priority
– Find / save the minimum element, delete it from
structure and return it
Priority Queue
insertdeleteMin
4
Implementation using Linked List
• Unsorted linked list
– insert takes O(1) time
– deleteMin takes O(N) time
• Sorted linked list
– insert takes O(N) time
– deleteMin takes O(1) time
5
Implementation using Binary Search Tree
• insert takes O(log N) time on the average
• deleteMin takes O(log N) time on the average
• support other operations that are not required by
priority queue (for example, findMax)
• deleteMin operations make the tree unbalanced
6
Binary Heap Implementation
• Property 1: Structure Property
• Binary tree & completely filled (bottom level is
filled from left to right) (complete binary tree)
• if height is h, size between 2h (bottom level has
only one node) and 2h+1-1
A
C
GF
B
E
J
D
H I
7
Array Implementation of Binary Heap
A
C
GF
B
E
J
D
H I
A B C D E F G H I J
0 1 2 3 4 5 6 7 8 9 10 11 12 13
left child is in position 2i
right child is in position (2i+1)
parent is in position floor(i/2)
or integer division in C
8
Property 2: Heap Order Property
(for Minimum Heap)
• Any node is smaller than (or equal to) all of
its children (any subtree is a heap)
• Smallest element is at the root (findMin take
O(1) time)
13
16
6819
21
31
32
24
65 26
9
Insert
13
16
6819
21
31
32
24
65 26
• Create a hole in the next available location
• Move the hole up (swap with its parent) until
data can be placed in the hole without violating
the heap order property (called percolate up)
13
16
6819
21
32
24
65 26 31
10
Insert
13
16
6819
21
31
32
24
65 26
13
16
6819
21
32
24
65 26 31
Percolate Up -> move the place to put 14 up
(move its parent down) until its parent <= 14
insert 14
11
Insert
13
16
681921
3132
24
65 26
13
16
681921
3132
24
65 26
14
12
deleteMin
• Create a hole at the root
• Move the hole down (swap with the smaller one
of its children) until the last element of the heap
can be placed in the hole without violating the
heap order property (called percolate down)
13
16
681921
3132
19
65 26
14 16
681921
32
19
65 26
14
31
13
deleteMin
13
16
681921
3132
19
65 26
14 16
681921
32
19
65 26
14
31
Percolate Down -> move the place to put 31 down
(move its smaller child up) until its children >= 31
14
deleteMin
16
681921
32
19
65 26
14
31
16
681921
32
19
65 26
14
31
15
deleteMin
16
681921
32
19
65
14
31
26
16
681921
32
19
65
26
14
31
16
Running Time
• insert
– worst case: takes O(log N) time, moves an element
from the bottom to the top
– on average: takes a constant time (2.607 comparisons),
moves an element up 1.607 levels
• deleteMin
– worst case: takes O(log N) time
– on average: takes O(log N) time (element that is placed
at the root is large, so it is percolated almost to the
bottom)
Implementation in C - HeapStruct
17
#define MinPQSize (10)
#define MinData (-32767)
typedef int ElementType;
struct HeapStruct
{
int Capacity;
int Size;
ElementType *Elements;
};
typedef struct HeapStruct *PriorityQueue;
Implementation in C - Initialize
18
PriorityQueue Initialize( int MaxElements )
{
PriorityQueue H;
if( MaxElements < MinPQSize )
Error( "Priority queue size is too small" );
H = malloc( sizeof( struct HeapStruct ) );
if( H ==NULL ) FatalError( "Out of space!!!" );
/* Allocate the array plus one extra for sentinel */
H->Elements = malloc((MaxElements + 1)*sizeof(ElementType));
if( H->Elements == NULL ) FatalError( "Out of space!!!" );
H->Capacity = MaxElements;
H->Size = 0;
H->Elements[ 0 ] = MinData;
return H;
}
19
int IsEmpty( PriorityQueue H )
{
return H->Size == 0;
}
int IsFull( PriorityQueue H )
{
return H->Size == H->Capacity;
}
Implementation in C – IsEmpty, IsFull
20
Implementation in C – Insert
/* H->Element[ 0 ] is a sentinel */
void Insert( ElementType X, PriorityQueue H )
{
int i;
if( IsFull( H ) )
{
Error( "Priority queue is full" );
return;
}
for( i = ++H->Size; H->Elements[ i / 2 ] > X; i /= 2 )
H->Elements[ i ] = H->Elements[ i / 2 ];
H->Elements[ i ] = X;
}
21
Implementation in C – DeleteMin
ElementType DeleteMin( PriorityQueue H )
{
ElementType MinElement;
if( IsEmpty( H ) )
{
Error( "Priority queue is empty" );
return H->Elements[0];
}
MinElement = H->Elements[ 1 ];
H->Elements[ 1 ] = H->Elements[ H->Size-- ];
percolateDown( H, 1 );
return MinElement;
}
22
Implementation in C – percolateDown
void percolateDown( PriorityQueue H, int hole )
{
int child;
ElementType tmp = H->Elements[ hole ];
for( ; hole * 2 <= H->Size; hole = child )
{
/* Find smaller child */
child = hole * 2;
if (child != H->Size && H->Elements[child+1]<H->Elements[child])
child++;
/* Percolate one level */
if( tmp > H->Elements[child] )
H->Elements[ hole ] = H->Elements[ child ];
else
break;
}
H->Elements[ hole ] = tmp;
}
Building a Heap
• Sometimes it is required to construct it from an
initial collection of items O(NlogN) in the worst
case.
• But insertions take O(1) on the average.
• Hence the question: is it possible to do any
better?
23
buildHeap Algorithm
• General Algorithm
• Place the N items into the tree in any order,
maintaining the structure property.
• Call buildHeap
24
void buildHeap( PriorityQueue H, int N )
{
int i;
for( i = N / 2; i > 0; i-- )
percolateDown( H, i );
}
buildHeap Example - I
25
initial
heap
after
percolateDown(7)
after
percolateDown(6)
after
percolateDown(5)
26
buildHeap Example - II
after
percolateDown(4)
after
percolateDown(3)
after
percolateDown(2)
after
percolateDown(1)
Complexity of buildHeap
• The number of dashed lines must be bounded which can simply
be done by computing the sum of the heights of all the nodes in
the heap.
• Theorem: For a perfect binary tree of height h with N=2h+1-1
nodes, this sum is 2h+1-1-(h+1).
• Proof:
• number of nodes in a complete tree of height h is less than or
equal to the the number of nodes in a perfect binary tree of the
same height. Therefore, O(N)
27
)1(1222...8422
)1(2...)3(16)2(8)1(4)(22
)1(2...)4(16)3(8)2(4)1(2)(1)(2
11
1
0
+−−=−+++++==−
++−+−+−+=
++−+−+−+−+=−=
+−
−
=
∑
hhSSS
hhhhS
hhhhhihS
hhh
h
h
h
i
i

More Related Content

What's hot

Ganga: an interface to the LHC computing grid
Ganga: an interface to the LHC computing gridGanga: an interface to the LHC computing grid
Ganga: an interface to the LHC computing gridMatt Williams
 
Engineering Fast Indexes for Big-Data Applications: Spark Summit East talk by...
Engineering Fast Indexes for Big-Data Applications: Spark Summit East talk by...Engineering Fast Indexes for Big-Data Applications: Spark Summit East talk by...
Engineering Fast Indexes for Big-Data Applications: Spark Summit East talk by...Spark Summit
 
Faster Workflows, Faster
Faster Workflows, FasterFaster Workflows, Faster
Faster Workflows, FasterKen Krugler
 
The Ring programming language version 1.9 book - Part 90 of 210
The Ring programming language version 1.9 book - Part 90 of 210The Ring programming language version 1.9 book - Part 90 of 210
The Ring programming language version 1.9 book - Part 90 of 210Mahmoud Samir Fayed
 
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemWprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemSages
 
Beyond tf idf why, what & how
Beyond tf idf why, what & howBeyond tf idf why, what & how
Beyond tf idf why, what & howlucenerevolution
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopSaša Tatar
 
Functional Reactive Programming with RxJS
Functional Reactive Programming with RxJSFunctional Reactive Programming with RxJS
Functional Reactive Programming with RxJSstefanmayer13
 
Stratosphere Intro (Java and Scala Interface)
Stratosphere Intro (Java and Scala Interface)Stratosphere Intro (Java and Scala Interface)
Stratosphere Intro (Java and Scala Interface)Robert Metzger
 
Spark 4th Meetup Londond - Building a Product with Spark
Spark 4th Meetup Londond - Building a Product with SparkSpark 4th Meetup Londond - Building a Product with Spark
Spark 4th Meetup Londond - Building a Product with Sparksamthemonad
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopSages
 
Functional linear data structures in f#
Functional linear data structures in f#Functional linear data structures in f#
Functional linear data structures in f#Jack Fox
 
HyperLogLog in Hive - How to count sheep efficiently?
HyperLogLog in Hive - How to count sheep efficiently?HyperLogLog in Hive - How to count sheep efficiently?
HyperLogLog in Hive - How to count sheep efficiently?bzamecnik
 
Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...
Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...
Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...Data Con LA
 

What's hot (20)

Ganga: an interface to the LHC computing grid
Ganga: an interface to the LHC computing gridGanga: an interface to the LHC computing grid
Ganga: an interface to the LHC computing grid
 
Stack Data structure
Stack Data structureStack Data structure
Stack Data structure
 
Engineering Fast Indexes for Big-Data Applications: Spark Summit East talk by...
Engineering Fast Indexes for Big-Data Applications: Spark Summit East talk by...Engineering Fast Indexes for Big-Data Applications: Spark Summit East talk by...
Engineering Fast Indexes for Big-Data Applications: Spark Summit East talk by...
 
Faster Workflows, Faster
Faster Workflows, FasterFaster Workflows, Faster
Faster Workflows, Faster
 
The Ring programming language version 1.9 book - Part 90 of 210
The Ring programming language version 1.9 book - Part 90 of 210The Ring programming language version 1.9 book - Part 90 of 210
The Ring programming language version 1.9 book - Part 90 of 210
 
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemWprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
 
Advanced locking
Advanced lockingAdvanced locking
Advanced locking
 
Beyond tf idf why, what & how
Beyond tf idf why, what & howBeyond tf idf why, what & how
Beyond tf idf why, what & how
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
 
Functional Reactive Programming with RxJS
Functional Reactive Programming with RxJSFunctional Reactive Programming with RxJS
Functional Reactive Programming with RxJS
 
Stratosphere Intro (Java and Scala Interface)
Stratosphere Intro (Java and Scala Interface)Stratosphere Intro (Java and Scala Interface)
Stratosphere Intro (Java and Scala Interface)
 
Dotnet 18
Dotnet 18Dotnet 18
Dotnet 18
 
Spark 4th Meetup Londond - Building a Product with Spark
Spark 4th Meetup Londond - Building a Product with SparkSpark 4th Meetup Londond - Building a Product with Spark
Spark 4th Meetup Londond - Building a Product with Spark
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache Hadoop
 
Angular2 rxjs
Angular2 rxjsAngular2 rxjs
Angular2 rxjs
 
Functional linear data structures in f#
Functional linear data structures in f#Functional linear data structures in f#
Functional linear data structures in f#
 
R and cpp
R and cppR and cpp
R and cpp
 
HyperLogLog in Hive - How to count sheep efficiently?
HyperLogLog in Hive - How to count sheep efficiently?HyperLogLog in Hive - How to count sheep efficiently?
HyperLogLog in Hive - How to count sheep efficiently?
 
Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...
Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...
Big Data Day LA 2015 - Large Scale Distinct Count -- The HyperLogLog algorith...
 
Heaps
HeapsHeaps
Heaps
 

Similar to 10 chapter6 heaps_priority_queues

Similar to 10 chapter6 heaps_priority_queues (20)

Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 
03-data-structures.pdf
03-data-structures.pdf03-data-structures.pdf
03-data-structures.pdf
 
lecture4.pdf
lecture4.pdflecture4.pdf
lecture4.pdf
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
 
linkedlist.pptx
linkedlist.pptxlinkedlist.pptx
linkedlist.pptx
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
 
STLStack.pdf
STLStack.pdfSTLStack.pdf
STLStack.pdf
 
DA_02_algorithms.pptx
DA_02_algorithms.pptxDA_02_algorithms.pptx
DA_02_algorithms.pptx
 
Data Structures and Files
Data Structures and FilesData Structures and Files
Data Structures and Files
 
Heap Tree.pdf
Heap Tree.pdfHeap Tree.pdf
Heap Tree.pdf
 
U3.stack queue
U3.stack queueU3.stack queue
U3.stack queue
 
Lec23
Lec23Lec23
Lec23
 
Stack and its applications
Stack and its applicationsStack and its applications
Stack and its applications
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Stack concepts by Divya
Stack concepts by DivyaStack concepts by Divya
Stack concepts by Divya
 
Recursion.ppt
Recursion.pptRecursion.ppt
Recursion.ppt
 
Heaps
HeapsHeaps
Heaps
 
Shell sort[1]
Shell sort[1]Shell sort[1]
Shell sort[1]
 
Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02
 
My lectures circular queue
My lectures circular queueMy lectures circular queue
My lectures circular queue
 

More from SSE_AndyLi

Chapter 07 Digital Alrithmetic and Arithmetic Circuits
Chapter 07 Digital Alrithmetic and Arithmetic CircuitsChapter 07 Digital Alrithmetic and Arithmetic Circuits
Chapter 07 Digital Alrithmetic and Arithmetic CircuitsSSE_AndyLi
 
Chapter 06 Combinational Logic Functions
Chapter 06 Combinational Logic FunctionsChapter 06 Combinational Logic Functions
Chapter 06 Combinational Logic FunctionsSSE_AndyLi
 
Chapter 5 introduction to VHDL
Chapter 5 introduction to VHDLChapter 5 introduction to VHDL
Chapter 5 introduction to VHDLSSE_AndyLi
 
Chapter 03 Boolean Algebra and Combinational Logic
Chapter 03 Boolean Algebra and Combinational LogicChapter 03 Boolean Algebra and Combinational Logic
Chapter 03 Boolean Algebra and Combinational LogicSSE_AndyLi
 
Chapter 02 Logic Functions and Gates
Chapter 02 Logic Functions and GatesChapter 02 Logic Functions and Gates
Chapter 02 Logic Functions and GatesSSE_AndyLi
 
Chapter 01 Basic Principles of Digital Systems
Chapter 01 Basic Principles of Digital SystemsChapter 01 Basic Principles of Digital Systems
Chapter 01 Basic Principles of Digital SystemsSSE_AndyLi
 
15 chapter9 graph_algorithms_mst
15 chapter9 graph_algorithms_mst15 chapter9 graph_algorithms_mst
15 chapter9 graph_algorithms_mstSSE_AndyLi
 
14 chapter9 graph_algorithmstopologicalsort_shortestpath
14 chapter9 graph_algorithmstopologicalsort_shortestpath14 chapter9 graph_algorithmstopologicalsort_shortestpath
14 chapter9 graph_algorithmstopologicalsort_shortestpathSSE_AndyLi
 
9 chapter4 trees_avl
9 chapter4 trees_avl9 chapter4 trees_avl
9 chapter4 trees_avlSSE_AndyLi
 
8 chapter4 trees_bst
8 chapter4 trees_bst8 chapter4 trees_bst
8 chapter4 trees_bstSSE_AndyLi
 
7 chapter4 trees_binary
7 chapter4 trees_binary7 chapter4 trees_binary
7 chapter4 trees_binarySSE_AndyLi
 
6 chapter3 list_stackqueuepart3
6 chapter3 list_stackqueuepart36 chapter3 list_stackqueuepart3
6 chapter3 list_stackqueuepart3SSE_AndyLi
 
5 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart25 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart2SSE_AndyLi
 
4 chapter3 list_stackqueuepart1
4 chapter3 list_stackqueuepart14 chapter3 list_stackqueuepart1
4 chapter3 list_stackqueuepart1SSE_AndyLi
 
3 chapter2 algorithm_analysispart2
3 chapter2 algorithm_analysispart23 chapter2 algorithm_analysispart2
3 chapter2 algorithm_analysispart2SSE_AndyLi
 
2 chapter2 algorithm_analysispart1
2 chapter2 algorithm_analysispart12 chapter2 algorithm_analysispart1
2 chapter2 algorithm_analysispart1SSE_AndyLi
 
1 chapter1 introduction
1 chapter1 introduction1 chapter1 introduction
1 chapter1 introductionSSE_AndyLi
 

More from SSE_AndyLi (17)

Chapter 07 Digital Alrithmetic and Arithmetic Circuits
Chapter 07 Digital Alrithmetic and Arithmetic CircuitsChapter 07 Digital Alrithmetic and Arithmetic Circuits
Chapter 07 Digital Alrithmetic and Arithmetic Circuits
 
Chapter 06 Combinational Logic Functions
Chapter 06 Combinational Logic FunctionsChapter 06 Combinational Logic Functions
Chapter 06 Combinational Logic Functions
 
Chapter 5 introduction to VHDL
Chapter 5 introduction to VHDLChapter 5 introduction to VHDL
Chapter 5 introduction to VHDL
 
Chapter 03 Boolean Algebra and Combinational Logic
Chapter 03 Boolean Algebra and Combinational LogicChapter 03 Boolean Algebra and Combinational Logic
Chapter 03 Boolean Algebra and Combinational Logic
 
Chapter 02 Logic Functions and Gates
Chapter 02 Logic Functions and GatesChapter 02 Logic Functions and Gates
Chapter 02 Logic Functions and Gates
 
Chapter 01 Basic Principles of Digital Systems
Chapter 01 Basic Principles of Digital SystemsChapter 01 Basic Principles of Digital Systems
Chapter 01 Basic Principles of Digital Systems
 
15 chapter9 graph_algorithms_mst
15 chapter9 graph_algorithms_mst15 chapter9 graph_algorithms_mst
15 chapter9 graph_algorithms_mst
 
14 chapter9 graph_algorithmstopologicalsort_shortestpath
14 chapter9 graph_algorithmstopologicalsort_shortestpath14 chapter9 graph_algorithmstopologicalsort_shortestpath
14 chapter9 graph_algorithmstopologicalsort_shortestpath
 
9 chapter4 trees_avl
9 chapter4 trees_avl9 chapter4 trees_avl
9 chapter4 trees_avl
 
8 chapter4 trees_bst
8 chapter4 trees_bst8 chapter4 trees_bst
8 chapter4 trees_bst
 
7 chapter4 trees_binary
7 chapter4 trees_binary7 chapter4 trees_binary
7 chapter4 trees_binary
 
6 chapter3 list_stackqueuepart3
6 chapter3 list_stackqueuepart36 chapter3 list_stackqueuepart3
6 chapter3 list_stackqueuepart3
 
5 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart25 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart2
 
4 chapter3 list_stackqueuepart1
4 chapter3 list_stackqueuepart14 chapter3 list_stackqueuepart1
4 chapter3 list_stackqueuepart1
 
3 chapter2 algorithm_analysispart2
3 chapter2 algorithm_analysispart23 chapter2 algorithm_analysispart2
3 chapter2 algorithm_analysispart2
 
2 chapter2 algorithm_analysispart1
2 chapter2 algorithm_analysispart12 chapter2 algorithm_analysispart1
2 chapter2 algorithm_analysispart1
 
1 chapter1 introduction
1 chapter1 introduction1 chapter1 introduction
1 chapter1 introduction
 

Recently uploaded

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 

Recently uploaded (20)

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 

10 chapter6 heaps_priority_queues

  • 1. Chapter 6: Priority Queues (Heaps) Text: Read Weiss, §6.1 – 6.3 1
  • 2. 2 Priority Queue (Heap) • A kind of queue • Dequeue gets element with the highest priority • Priority is based on a comparable value (key) of each object (smaller value higher priority, or higher value higher priority) • Example Applications: – printer -> print (dequeue) the shortest document first – operating system -> run (dequeue) the shortest job first – normal queue -> dequeue the first enqueued element first
  • 3. 3 Priority Queue (Heap) Operations • insert (enqueue) • deleteMin (dequeue) – smaller value higher priority – Find / save the minimum element, delete it from structure and return it Priority Queue insertdeleteMin
  • 4. 4 Implementation using Linked List • Unsorted linked list – insert takes O(1) time – deleteMin takes O(N) time • Sorted linked list – insert takes O(N) time – deleteMin takes O(1) time
  • 5. 5 Implementation using Binary Search Tree • insert takes O(log N) time on the average • deleteMin takes O(log N) time on the average • support other operations that are not required by priority queue (for example, findMax) • deleteMin operations make the tree unbalanced
  • 6. 6 Binary Heap Implementation • Property 1: Structure Property • Binary tree & completely filled (bottom level is filled from left to right) (complete binary tree) • if height is h, size between 2h (bottom level has only one node) and 2h+1-1 A C GF B E J D H I
  • 7. 7 Array Implementation of Binary Heap A C GF B E J D H I A B C D E F G H I J 0 1 2 3 4 5 6 7 8 9 10 11 12 13 left child is in position 2i right child is in position (2i+1) parent is in position floor(i/2) or integer division in C
  • 8. 8 Property 2: Heap Order Property (for Minimum Heap) • Any node is smaller than (or equal to) all of its children (any subtree is a heap) • Smallest element is at the root (findMin take O(1) time) 13 16 6819 21 31 32 24 65 26
  • 9. 9 Insert 13 16 6819 21 31 32 24 65 26 • Create a hole in the next available location • Move the hole up (swap with its parent) until data can be placed in the hole without violating the heap order property (called percolate up) 13 16 6819 21 32 24 65 26 31
  • 10. 10 Insert 13 16 6819 21 31 32 24 65 26 13 16 6819 21 32 24 65 26 31 Percolate Up -> move the place to put 14 up (move its parent down) until its parent <= 14 insert 14
  • 12. 12 deleteMin • Create a hole at the root • Move the hole down (swap with the smaller one of its children) until the last element of the heap can be placed in the hole without violating the heap order property (called percolate down) 13 16 681921 3132 19 65 26 14 16 681921 32 19 65 26 14 31
  • 13. 13 deleteMin 13 16 681921 3132 19 65 26 14 16 681921 32 19 65 26 14 31 Percolate Down -> move the place to put 31 down (move its smaller child up) until its children >= 31
  • 16. 16 Running Time • insert – worst case: takes O(log N) time, moves an element from the bottom to the top – on average: takes a constant time (2.607 comparisons), moves an element up 1.607 levels • deleteMin – worst case: takes O(log N) time – on average: takes O(log N) time (element that is placed at the root is large, so it is percolated almost to the bottom)
  • 17. Implementation in C - HeapStruct 17 #define MinPQSize (10) #define MinData (-32767) typedef int ElementType; struct HeapStruct { int Capacity; int Size; ElementType *Elements; }; typedef struct HeapStruct *PriorityQueue;
  • 18. Implementation in C - Initialize 18 PriorityQueue Initialize( int MaxElements ) { PriorityQueue H; if( MaxElements < MinPQSize ) Error( "Priority queue size is too small" ); H = malloc( sizeof( struct HeapStruct ) ); if( H ==NULL ) FatalError( "Out of space!!!" ); /* Allocate the array plus one extra for sentinel */ H->Elements = malloc((MaxElements + 1)*sizeof(ElementType)); if( H->Elements == NULL ) FatalError( "Out of space!!!" ); H->Capacity = MaxElements; H->Size = 0; H->Elements[ 0 ] = MinData; return H; }
  • 19. 19 int IsEmpty( PriorityQueue H ) { return H->Size == 0; } int IsFull( PriorityQueue H ) { return H->Size == H->Capacity; } Implementation in C – IsEmpty, IsFull
  • 20. 20 Implementation in C – Insert /* H->Element[ 0 ] is a sentinel */ void Insert( ElementType X, PriorityQueue H ) { int i; if( IsFull( H ) ) { Error( "Priority queue is full" ); return; } for( i = ++H->Size; H->Elements[ i / 2 ] > X; i /= 2 ) H->Elements[ i ] = H->Elements[ i / 2 ]; H->Elements[ i ] = X; }
  • 21. 21 Implementation in C – DeleteMin ElementType DeleteMin( PriorityQueue H ) { ElementType MinElement; if( IsEmpty( H ) ) { Error( "Priority queue is empty" ); return H->Elements[0]; } MinElement = H->Elements[ 1 ]; H->Elements[ 1 ] = H->Elements[ H->Size-- ]; percolateDown( H, 1 ); return MinElement; }
  • 22. 22 Implementation in C – percolateDown void percolateDown( PriorityQueue H, int hole ) { int child; ElementType tmp = H->Elements[ hole ]; for( ; hole * 2 <= H->Size; hole = child ) { /* Find smaller child */ child = hole * 2; if (child != H->Size && H->Elements[child+1]<H->Elements[child]) child++; /* Percolate one level */ if( tmp > H->Elements[child] ) H->Elements[ hole ] = H->Elements[ child ]; else break; } H->Elements[ hole ] = tmp; }
  • 23. Building a Heap • Sometimes it is required to construct it from an initial collection of items O(NlogN) in the worst case. • But insertions take O(1) on the average. • Hence the question: is it possible to do any better? 23
  • 24. buildHeap Algorithm • General Algorithm • Place the N items into the tree in any order, maintaining the structure property. • Call buildHeap 24 void buildHeap( PriorityQueue H, int N ) { int i; for( i = N / 2; i > 0; i-- ) percolateDown( H, i ); }
  • 25. buildHeap Example - I 25 initial heap after percolateDown(7) after percolateDown(6) after percolateDown(5)
  • 26. 26 buildHeap Example - II after percolateDown(4) after percolateDown(3) after percolateDown(2) after percolateDown(1)
  • 27. Complexity of buildHeap • The number of dashed lines must be bounded which can simply be done by computing the sum of the heights of all the nodes in the heap. • Theorem: For a perfect binary tree of height h with N=2h+1-1 nodes, this sum is 2h+1-1-(h+1). • Proof: • number of nodes in a complete tree of height h is less than or equal to the the number of nodes in a perfect binary tree of the same height. Therefore, O(N) 27 )1(1222...8422 )1(2...)3(16)2(8)1(4)(22 )1(2...)4(16)3(8)2(4)1(2)(1)(2 11 1 0 +−−=−+++++==− ++−+−+−+= ++−+−+−+−+=−= +− − = ∑ hhSSS hhhhS hhhhhihS hhh h h h i i