Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny...

48
CSC212 Data Structure - Section FG Lecture 18 Heaps and Priority Queues Instructor: Feng HU Department of Computer Science City College of New York

Transcript of Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny...

Page 1: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

CSC212 Data Structure

- Section FG

Lecture18HeapsandPriorityQueues

Instructor:FengHUDepartmentofComputerScience

CityCollegeofNewYork

Page 2: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

Heaps

•Chapter11hasseveralprogrammingprojects,includingaprojectthatusesheaps.

• Thispresentationshowsyouwhataheapis,anddemonstratestwooftheimportantheapalgorithms.

Data Structuresand Other ObjectsUsing C++

Page 3: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

Topics

•HeapDefinition•HeapApplications

• priorityqueues(chapter8),sorting(chapter13)• TwoHeapOperations– add,remove

• reheapificationupwardanddownward• whyisaheapgoodforimplementingapriorityqueue?

•HeapImplementation• usingbinary_tree_nodeclass• usingfixedsizeordynamicarrays

Page 4: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

HeapsDefinition

Aheapisacertainkindofcompletebinarytree.

Page 5: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

Heaps

Aheap isacertainkindofcompletebinarytree.

When a completebinary tree is built,

its first node must bethe root.

Root

Page 6: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

Heaps

Completebinarytree. Left childof theroot

The second node isalways the left child

of the root.

Page 7: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

Heaps

Completebinarytree. Right childof the

root

The third node isalways the right child

of the root.

Page 8: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

Heaps

Completebinarytree.

The next nodesalways fill the next

level from left-to-right.

Page 9: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

Heaps

Completebinarytree.

The next nodesalways fill the next

level from left-to-right.

Page 10: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

Heaps

Completebinarytree.

The next nodesalways fill the next

level from left-to-right.

Page 11: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

Heaps

Completebinarytree.

The next nodesalways fill the next

level from left-to-right.

Page 12: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

Heaps

Completebinarytree.

Page 13: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

Heaps

Aheapisacertainkindofcompletebinarytree.

Each node in a heapcontains a key thatcan be compared toother nodes' keys.

19

4222127

23

45

35

Page 14: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

Heaps

Aheapisacertainkindofcompletebinarytree.

The "heap property"requires that each

node's key is >= thekeys of its children

19

4222127

23

45

35

Page 15: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

Whatitisnot:ItisnotaBST

• Inabinarysearchtree,theentriesofthenodescanbecomparedwithastrictweakordering.Tworulesarefollowedforeverynoden:

• TheentryinnodenisNEVERlessthan anentryinitsleftsubtree• Theentryinthenodenislessthan everyentryinitsright subtree.

• BSTisnotnecessarilyacompletetree

Page 16: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

Whatitis:HeapDefinition

• Aheapisabinarytreewheretheentriesofthenodescanbecomparedwiththelessthan operatorofastrictweakordering.Inaddition,tworulesarefollowed:

• TheentrycontainedbythenodeisNEVERlessthan theentriesofthenode’schildren

• ThetreeisaCOMPLETEtree.

• Q:whereisthelargestentry?à forwhat....

Page 17: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

Application:PriorityQueues

• Apriorityqueueisacontainerclassthatallowsentriestoberetrievedaccordingtosomespecificprioritylevels

• Thehighestpriorityentryisremoved first• Ifthereareseveralentrieswithequallyhighpriorities, thenthepriorityqueue’s implementationdetermineswhichwillcomeoutfirst(e.g.FIFO)

• Heapissuitableforapriorityqueue

Page 18: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

ThePriorityQueueADTwithHeaps

• Theentrywiththehighestpriorityisalwaysattherootnode

• Focusontwopriorityqueueoperations• addinganewentry• removetheentrywiththehighestpriority

• Inbothcases,wemustensurethetreestructureremainstobeaheap• wearegoingtoworkonaconceptualheapwithoutworryingaboutthepreciseimplementation

• laterIamgoingtoshowyouhowtoimplement...

Page 19: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

AddingaNodetoaHeap

❶ Putthenewnodeinthenextavailablespot.

❷ Pushthenewnodeupward,swappingwithitsparentuntilthenewnodereachesanacceptablelocation.

19

4222127

23

45

35

42

Page 20: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

AddingaNodetoaHeap

❶ Putthenewnodeinthenextavailablespot.

❷ Pushthenewnodeupward,swappingwithitsparentuntilthenewnodereachesanacceptablelocation.

19

4222142

23

45

35

27

Page 21: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

AddingaNodetoaHeap

❶ Putthenewnodeinthenextavailablespot.

❷ Pushthenewnodeupward,swappingwithitsparentuntilthenewnodereachesanacceptablelocation.

19

4222135

23

45

42

27

Page 22: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

AddingaNodetoaHeap

✔Theparenthasakeythatis>=newnode,or

✔Thenodereachestheroot.➚ Theprocessofpushingthe

newnodeupwardiscalledreheapificationupward. 19

4222135

23

45

42

27

Note: Note: we need to easily go from child to parent as well as parent to child.

Page 23: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

RemovingtheTopofaHeap

❶Movethelastnodeontotheroot.

19

4222135

23

45

42

27

Page 24: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

RemovingtheTopofaHeap

❶Movethelastnodeontotheroot.

19

4222135

23

27

42

Page 25: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

RemovingtheTopofaHeap

❶Movethelastnodeontotheroot.

❷ Pushtheout-of-placenodedownward,swappingwithitslargerchilduntilthenewnodereachesanacceptablelocation. 19

4222135

23

27

42

Page 26: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

RemovingtheTopofaHeap

❶Movethelastnodeontotheroot.

❷ Pushtheout-of-placenodedownward,swappingwithitslargerchilduntilthenewnodereachesanacceptablelocation. 19

4222135

23

42

27

Page 27: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

RemovingtheTopofaHeap

❶Movethelastnodeontotheroot.

❷ Pushtheout-of-placenodedownward,swappingwithitslargerchilduntilthenewnodereachesanacceptablelocation. 19

4222127

23

42

35

Page 28: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

RemovingtheTopofaHeap

✔Thechildrenallhavekeys<=theout-of-placenode,or

✔Thenodereachestheleaf.

➘ Theprocessofpushingthenewnodedownwardiscalledreheapificationdownward.

19

4222127

23

42

35

Page 29: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

PriorityQueuesRevisited

• Apriorityqueueisacontainerclassthatallowsentriestoberetrievedaccordingtosomespecificprioritylevels

• Thehighestpriorityentryisremoved first• Ifthereareseveralentrieswithequallyhighpriorities,thenthepriorityqueue’simplementationdetermineswhichwill comeoutfirst(e.g.FIFO)

• Heapissuitableforapriorityqueue

Page 30: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

AddingaNode:samepriority

❶ Putthenewnodeinthenextavailablespot.

❷ Pushthenewnodeupward,swappingwithitsparentuntilthenewnodereachesanacceptablelocation.

19

4222127

23

45

35

45*

Page 31: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

AddingaNode:samepriority

❶ Putthenewnodeinthenextavailablespot.

❷ Pushthenewnodeupward,swappingwithitsparentuntilthenewnodereachesanacceptablelocation.

19

4222145*

23

45

35

27

Page 32: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

AddingaNode:samepriority

❶ Putthenewnodeinthenextavailablespot.

❷ Pushthenewnodeupward,swappingwithitsparentuntilthenewnodereachesanacceptablelocation.

19

4222135

23

45

45*

27

Page 33: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

AddingaNode:samepriority

✔Theparenthasakeythatis>=newnode,or

✔Thenodereachestheroot.➚ Theprocessofpushingthe

newnodeupwardiscalledreheapificationupward. 19

4222135

23

45

45*

27

Note: Implementation determines which 45 will be in the root, and will come out first when popping.

Page 34: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

RemovingtheTopofaHeap

✔Thechildrenallhavekeys<=theout-of-placenode,or

✔Thenodereachestheleaf.➘ Theprocessofpushingthe

newnodedownwardiscalledreheapificationdownward. 19

4222127

23

45*

35

Note: Implementation determines which 45 will be in the root, and will come out first when popping.

Page 35: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

HeapImplementation

• Usebinary_tree_nodeclass• node implementation isforageneralbinarytree• butwemayneedtohavedoubly linkednode

• Usearrays(page475)• Aheapisacompletebinarytree• whichcanbeimplementedmoreeasilywithanarraythanwiththenodeclass

• anddotwo-waylinks

Page 36: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

Formulasforlocationchildrenandparentsinanarrayrepresentation

• Rootatlocation[0]• Parentofthenodein[i]isat[(i-1)/2]• Childrenofthenodein[i](ifexist)isat[2i+1]and[2i+2]• Test:

• completetreeof10,000nodes• parentof4999isat(4999-1)/2=2499• childrenof4999isat9999(V)and10,000(X)

Page 37: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

ImplementingaHeap

• Wewillstorethedatafromthenodesinapartially-filledarray.

An array of data

2127

23

42

35

Page 38: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

ImplementingaHeap

• Datafromtherootgoesinthe firstlocationofthearray.

An array of data

2127

23

42

35

42

Page 39: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

ImplementingaHeap

• Datafromthenextrowgoes inthenexttwoarraylocations.

An array of data

2127

23

42

35

42 35 23

Page 40: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

ImplementingaHeap

• Datafromthenextrowgoes inthenexttwoarraylocations.

An array of data

2127

23

42

35

42 35 23 27 21

Page 41: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

ImplementingaHeap

• Datafromthenextrowgoes inthenexttwoarraylocations.

An array of data

2127

23

42

35

42 35 23 27 21

We don't care what's inthis part of the array.

Page 42: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

ImportantPointsabouttheImplementation

• Thelinksbetweenthetree'snodesarenot actuallystoredaspointers,orinanyotherway.

• Theonlywaywe"know"that"thearrayisatree"isfromthewaywemanipulatethedata.

An array of data

2127

23

42

35

42 35 23 27 21

Page 43: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

ImportantPointsabouttheImplementation

• Ifyouknowtheindexofanode,thenitiseasytofigureouttheindexesofthatnode'sparentandchildren.Formulasaregiveninthebook.

[0] [1] [2] [3] [4]

2127

23

42

35

42 35 23 27 21

Page 44: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

Formulasforlocationchildrenandparentsinanarrayrepresentation

• Rootatlocation[0]• Parentofthenodein[i]isat[(i-1)/2]• Childrenofthenodein[i](ifexist)isat[2i+1]and[2i+2]• Test:

• completetreeof10,000nodes• parentof4999isat(4999-1)/2=2499• childrenof4999isat9999(V)and10,000(X)

Page 45: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

WrapUp...

• Canyouimplement theaddandremovewiththeknowledgeoftheseformulas?

• Add• putthenewentryinthelastlocation• Pushthenewnodeupward,swappingwithitsparentuntilthenewnodereachesanacceptablelocation

• Remove• movethelastnodetotheroot• Pushtheout-of-placenodedownward,swappingwithits largerchilduntilthenewnodereachesanacceptable location

class heap{public:

....void push(const Item& entry); // addItem& pop(); // remove the highest

private:Item data[CAPACITY];size_type used;

}

Page 46: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

WrapUp...

• Canyouimplement theaddandremovewiththeknowledgeoftheseformulas?

• Add(in-classquiz)• putthenewentryinthelastlocation

• Pushthenewnodeupward,swappingwithitsparentuntilthenewnodereachesanacceptable location

• Remove(in-classquiz)• movethelastnodetotheroot• Pushtheout-of-placenodedownward,swappingwithitslargerchilduntilthenewnodereachesanacceptablelocation

template <class Item>class heap{public:

heap () { used = 0;}void push(const Item& entry); // addItem& pop(); // remove the highestsize_t parent (size_t k) const { return (k-1)/2;}size_t l_child (size_t k) const { return 2*k+1;}size_t r_child (size_t k) const { return 2*k+2;}

private:Item data[CAPACITY];size_type used;

}

Page 47: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

Summary

•Aheapisacompletebinarytree,wheretheentryateachnodeisgreaterthanorequaltotheentriesinitschildren.

• Toaddanentrytoaheap,placethenewentryatthenextavailablespot,andperformareheapificationupward.

• Toremovethebiggestentry,movethelastnodeontotheroot,andperformareheapificationdownward.

Page 48: Lecture 18 Heaps and Priority Queues - visionlab.engr.ccny ...visionlab.engr.ccny.cuny.edu/~fhu/Lecture18-Heaps.pdfLecture 18 Heaps and Priority Queues Instructor: ... heap is , and

THE END

Presentation copyright 1997 Addison Wesley Longman,For use with Data Structures and Other Objects Using C++by Michael Main and Walter Savitch.

Some artwork in the presentation is used with permission from Presentation Task Force(copyright New Vision Technologies Inc) and Corel Gallery Clipart Catalog (copyrightCorel Corporation, 3G Graphics Inc, Archive Arts, Cartesia Software, Image ClubGraphics Inc, One Mile Up Inc, TechPool Studios, Totem Graphics Inc).

Students and instructors who use Data Structures and Other Objects Using C++ are welcometo use this presentation however they see fit, so long as this copyright notice remainsintact.