SlideShare a Scribd company logo
1 of 20
Heaps and heapsort
COMP171
Fall 2005
Motivating Example
3 jobs have been submitted to a printer in the order A, B, C.
Sizes: Job A – 100 pages
Job B – 10 pages
Job C -- 1 page
Average waiting time with FIFO service:
(100+110+111) / 3 = 107 time units
Average waiting time for shortest-job-first service:
(1+11+111) / 3 = 41 time units
Need to have a queue which does insert and deletemin
Priority Queue
Common Implementations
1) Linked list
Insert in O(1)
Find the minimum element in O(n),
thus deletion is O(n)
2) Search Tree (AVL tree, to be covered later)
Insert in O(log n)
Delete in O(log n)
Search tree is an overkill as it does many other
operations
Heaps
Heaps are “almost complete binary trees”
-- All levels are full except possibly the lowest level.
If the lowest level is not full, then then nodes must be packed
to the left.
Note: we define “complete tree” slightly different from the book.
Binary Trees
• Has a root at the topmost level
• Each node has zero, one or two children
• A node that has no child is called a leaf
• For a node x, we denote the left child, right child and the
parent of x as left(x), right(x) and parent(x), respectively.
Binary trees
A complete tree An almost complete tree
A complete binary tree is one where a node can have 0 (for the leaves) or 2
children and all leaves are at the same depth.
Height (depth) of a binary tree
• The number of edges on the longest path from the root to a
leaf.
Height = 4
Height of a binary tree
• A complete binary tree of N nodes has height O(log N)
d 2d
Total: 2d+1
- 1
Proof
Prove by induction that number of nodes at depth d is 2d
Total number of nodes of a complete binary tree of depth d is 1 + 2 + 4 +……
2d
= 2d+1
- 1
Thus 2d+1
- 1 = N
d = log(N + 1) - 1 = O(log N)
What is the largest depth of a binary tree of N nodes? N
Heap property: the value at each node is less than or equal to
that of its descendants.
4
2
5
61 3
not a heap
1
2
5
64 3
A heap
Coming back to Heap
Heap
• Heap supports the following operations efficiently
• Locate the current minimum in O(1) time
• Delete the current minimum in O(log N) time
Insertion
• Add the new element to the lowest level
• Restore the min-heap property if violated:
• “bubble up”: if the parent of the element is larger than the element, then
interchange the parent and child.
1
2 5
64 3
1
2 5
64 3 2.5
1
2 2.5
64 3 5
Insert 2.5
Percolate up to maintain the heap property
Insertion
A heap!
DeleteMin: first attempt
Delete the root.
Compare the two children of the root
Make the lesser of the two the root.
An empty spot is created.
Bring the lesser of the two children of the empty spot
to the empty spot.
A new empty spot is created.
Continue
1
2
5
64 3
2
5
64 3
2
5
64 3
2
3
5
64
Heap property is preserved, but completeness is not preserved!
DeleteMin
1. Copy the last number to the root (i.e. overwrite the minimum
element stored there)
2. Restore the min-heap property by “bubble down”
Heapsort 1
Heapsort 1

More Related Content

What's hot

Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Anand Ingle
 
Build 2017 - B8037 - Explore the next generation of innovative UI in the Visu...
Build 2017 - B8037 - Explore the next generation of innovative UI in the Visu...Build 2017 - B8037 - Explore the next generation of innovative UI in the Visu...
Build 2017 - B8037 - Explore the next generation of innovative UI in the Visu...Windows Developer
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort AlgorithmLemia Algmri
 
Analysis of Algorithms-Heapsort
Analysis of Algorithms-HeapsortAnalysis of Algorithms-Heapsort
Analysis of Algorithms-HeapsortReetesh Gupta
 
lecture 5
lecture 5lecture 5
lecture 5sajinsc
 
Programming the cloud with Skywriting
Programming the cloud with SkywritingProgramming the cloud with Skywriting
Programming the cloud with SkywritingDerek Murray
 
lecture 13
lecture 13lecture 13
lecture 13sajinsc
 
MBrace: Large-scale cloud computation with F# (CUFP 2014)
MBrace: Large-scale cloud computation with F# (CUFP 2014)MBrace: Large-scale cloud computation with F# (CUFP 2014)
MBrace: Large-scale cloud computation with F# (CUFP 2014)Eirik George Tsarpalis
 
Heaps
HeapsHeaps
HeapsIIUM
 
Elixir 5 minute intro
Elixir 5 minute introElixir 5 minute intro
Elixir 5 minute introDoug Goldie
 

What's hot (20)

Binomial Heaps
Binomial HeapsBinomial Heaps
Binomial Heaps
 
Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure
 
Heap_Sort1.pptx
Heap_Sort1.pptxHeap_Sort1.pptx
Heap_Sort1.pptx
 
Build 2017 - B8037 - Explore the next generation of innovative UI in the Visu...
Build 2017 - B8037 - Explore the next generation of innovative UI in the Visu...Build 2017 - B8037 - Explore the next generation of innovative UI in the Visu...
Build 2017 - B8037 - Explore the next generation of innovative UI in the Visu...
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort Algorithm
 
Analysis of Algorithms-Heapsort
Analysis of Algorithms-HeapsortAnalysis of Algorithms-Heapsort
Analysis of Algorithms-Heapsort
 
lecture 5
lecture 5lecture 5
lecture 5
 
Binomial queues
Binomial queuesBinomial queues
Binomial queues
 
Programming the cloud with Skywriting
Programming the cloud with SkywritingProgramming the cloud with Skywriting
Programming the cloud with Skywriting
 
C07.heaps
C07.heapsC07.heaps
C07.heaps
 
lecture 13
lecture 13lecture 13
lecture 13
 
Heapsort
HeapsortHeapsort
Heapsort
 
MBrace: Cloud Computing with F#
MBrace: Cloud Computing with F#MBrace: Cloud Computing with F#
MBrace: Cloud Computing with F#
 
MBrace: Large-scale cloud computation with F# (CUFP 2014)
MBrace: Large-scale cloud computation with F# (CUFP 2014)MBrace: Large-scale cloud computation with F# (CUFP 2014)
MBrace: Large-scale cloud computation with F# (CUFP 2014)
 
Heaps
HeapsHeaps
Heaps
 
Heap
HeapHeap
Heap
 
Matchbox Mayhem
Matchbox MayhemMatchbox Mayhem
Matchbox Mayhem
 
Heap sort
Heap sortHeap sort
Heap sort
 
Elixir 5 minute intro
Elixir 5 minute introElixir 5 minute intro
Elixir 5 minute intro
 
Heapsort using Heap
Heapsort using HeapHeapsort using Heap
Heapsort using Heap
 

Similar to Heapsort 1

Applicationof datastructures
Applicationof datastructuresApplicationof datastructures
Applicationof datastructuresHitesh Wagle
 
Applicationof datastructures
Applicationof datastructuresApplicationof datastructures
Applicationof datastructuresHitesh Wagle
 
358 33 powerpoint-slides_12-heaps_chapter-12
358 33 powerpoint-slides_12-heaps_chapter-12358 33 powerpoint-slides_12-heaps_chapter-12
358 33 powerpoint-slides_12-heaps_chapter-12sumitbardhan
 
CS-102 BT_24_3_14 Binary Tree Lectures.pdf
CS-102 BT_24_3_14 Binary Tree Lectures.pdfCS-102 BT_24_3_14 Binary Tree Lectures.pdf
CS-102 BT_24_3_14 Binary Tree Lectures.pdfssuser034ce1
 
Algorithm chapter 6
Algorithm chapter 6Algorithm chapter 6
Algorithm chapter 6chidabdu
 
7 chapter4 trees_binary
7 chapter4 trees_binary7 chapter4 trees_binary
7 chapter4 trees_binarySSE_AndyLi
 
1. Briefly state the Master Theorem.What type of problem is it usefu.pdf
1. Briefly state the Master Theorem.What type of problem is it usefu.pdf1. Briefly state the Master Theorem.What type of problem is it usefu.pdf
1. Briefly state the Master Theorem.What type of problem is it usefu.pdfsales98
 
Applications of datastructures
Applications of datastructuresApplications of datastructures
Applications of datastructuresRatsietsi Mokete
 
Review session2
Review session2Review session2
Review session2NEEDY12345
 
Algo-Exercises-2-hash-AVL-Tree.ppt
Algo-Exercises-2-hash-AVL-Tree.pptAlgo-Exercises-2-hash-AVL-Tree.ppt
Algo-Exercises-2-hash-AVL-Tree.pptHebaSamy22
 

Similar to Heapsort 1 (20)

Sorting
SortingSorting
Sorting
 
Applicationof datastructures
Applicationof datastructuresApplicationof datastructures
Applicationof datastructures
 
Applicationof datastructures
Applicationof datastructuresApplicationof datastructures
Applicationof datastructures
 
b-tree.ppt
b-tree.pptb-tree.ppt
b-tree.ppt
 
Btreesprogramme
BtreesprogrammeBtreesprogramme
Btreesprogramme
 
358 33 powerpoint-slides_12-heaps_chapter-12
358 33 powerpoint-slides_12-heaps_chapter-12358 33 powerpoint-slides_12-heaps_chapter-12
358 33 powerpoint-slides_12-heaps_chapter-12
 
Binary trees1
Binary trees1Binary trees1
Binary trees1
 
CS-102 BT_24_3_14 Binary Tree Lectures.pdf
CS-102 BT_24_3_14 Binary Tree Lectures.pdfCS-102 BT_24_3_14 Binary Tree Lectures.pdf
CS-102 BT_24_3_14 Binary Tree Lectures.pdf
 
Algorithm chapter 6
Algorithm chapter 6Algorithm chapter 6
Algorithm chapter 6
 
Analysis of algo
Analysis of algoAnalysis of algo
Analysis of algo
 
7 chapter4 trees_binary
7 chapter4 trees_binary7 chapter4 trees_binary
7 chapter4 trees_binary
 
Lecture3
Lecture3Lecture3
Lecture3
 
B trees
B treesB trees
B trees
 
1. Briefly state the Master Theorem.What type of problem is it usefu.pdf
1. Briefly state the Master Theorem.What type of problem is it usefu.pdf1. Briefly state the Master Theorem.What type of problem is it usefu.pdf
1. Briefly state the Master Theorem.What type of problem is it usefu.pdf
 
Applications of datastructures
Applications of datastructuresApplications of datastructures
Applications of datastructures
 
Review session2
Review session2Review session2
Review session2
 
Heapsort ppt
Heapsort pptHeapsort ppt
Heapsort ppt
 
Red Black Trees
Red Black TreesRed Black Trees
Red Black Trees
 
Linear sorting
Linear sortingLinear sorting
Linear sorting
 
Algo-Exercises-2-hash-AVL-Tree.ppt
Algo-Exercises-2-hash-AVL-Tree.pptAlgo-Exercises-2-hash-AVL-Tree.ppt
Algo-Exercises-2-hash-AVL-Tree.ppt
 

More from sana younas

7 habits of highly effective people
7 habits of highly effective people7 habits of highly effective people
7 habits of highly effective peoplesana younas
 
Connectivity of graphs
Connectivity of graphsConnectivity of graphs
Connectivity of graphssana younas
 
Shortest path algorithm
Shortest path algorithmShortest path algorithm
Shortest path algorithmsana younas
 
circular linklist
circular linklistcircular linklist
circular linklistsana younas
 
Enterpise system
Enterpise systemEnterpise system
Enterpise systemsana younas
 
Database administration
Database administrationDatabase administration
Database administrationsana younas
 
Universal logic gate
Universal logic gateUniversal logic gate
Universal logic gatesana younas
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programmingsana younas
 
Memory management
Memory managementMemory management
Memory managementsana younas
 

More from sana younas (16)

7 habits of highly effective people
7 habits of highly effective people7 habits of highly effective people
7 habits of highly effective people
 
Connectivity of graphs
Connectivity of graphsConnectivity of graphs
Connectivity of graphs
 
Shortest path algorithm
Shortest path algorithmShortest path algorithm
Shortest path algorithm
 
Binary search
Binary searchBinary search
Binary search
 
circular linklist
circular linklistcircular linklist
circular linklist
 
Link list 2
Link list 2Link list 2
Link list 2
 
Link list 1
Link list 1Link list 1
Link list 1
 
Arrays
ArraysArrays
Arrays
 
Enterpise system
Enterpise systemEnterpise system
Enterpise system
 
Database administration
Database administrationDatabase administration
Database administration
 
Encoders
EncodersEncoders
Encoders
 
Universal logic gate
Universal logic gateUniversal logic gate
Universal logic gate
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Memory management
Memory managementMemory management
Memory management
 
Parallel adders
Parallel addersParallel adders
Parallel adders
 

Recently uploaded

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonJericReyAuditor
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 

Recently uploaded (20)

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lesson
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 

Heapsort 1

  • 2. Motivating Example 3 jobs have been submitted to a printer in the order A, B, C. Sizes: Job A – 100 pages Job B – 10 pages Job C -- 1 page Average waiting time with FIFO service: (100+110+111) / 3 = 107 time units Average waiting time for shortest-job-first service: (1+11+111) / 3 = 41 time units Need to have a queue which does insert and deletemin Priority Queue
  • 3. Common Implementations 1) Linked list Insert in O(1) Find the minimum element in O(n), thus deletion is O(n) 2) Search Tree (AVL tree, to be covered later) Insert in O(log n) Delete in O(log n) Search tree is an overkill as it does many other operations
  • 4. Heaps Heaps are “almost complete binary trees” -- All levels are full except possibly the lowest level. If the lowest level is not full, then then nodes must be packed to the left. Note: we define “complete tree” slightly different from the book.
  • 5. Binary Trees • Has a root at the topmost level • Each node has zero, one or two children • A node that has no child is called a leaf • For a node x, we denote the left child, right child and the parent of x as left(x), right(x) and parent(x), respectively.
  • 6. Binary trees A complete tree An almost complete tree A complete binary tree is one where a node can have 0 (for the leaves) or 2 children and all leaves are at the same depth.
  • 7. Height (depth) of a binary tree • The number of edges on the longest path from the root to a leaf. Height = 4
  • 8. Height of a binary tree • A complete binary tree of N nodes has height O(log N) d 2d Total: 2d+1 - 1
  • 9. Proof Prove by induction that number of nodes at depth d is 2d Total number of nodes of a complete binary tree of depth d is 1 + 2 + 4 +…… 2d = 2d+1 - 1 Thus 2d+1 - 1 = N d = log(N + 1) - 1 = O(log N) What is the largest depth of a binary tree of N nodes? N
  • 10. Heap property: the value at each node is less than or equal to that of its descendants. 4 2 5 61 3 not a heap 1 2 5 64 3 A heap Coming back to Heap
  • 11. Heap • Heap supports the following operations efficiently • Locate the current minimum in O(1) time • Delete the current minimum in O(log N) time
  • 12. Insertion • Add the new element to the lowest level • Restore the min-heap property if violated: • “bubble up”: if the parent of the element is larger than the element, then interchange the parent and child.
  • 13. 1 2 5 64 3 1 2 5 64 3 2.5 1 2 2.5 64 3 5 Insert 2.5 Percolate up to maintain the heap property
  • 14.
  • 16. DeleteMin: first attempt Delete the root. Compare the two children of the root Make the lesser of the two the root. An empty spot is created. Bring the lesser of the two children of the empty spot to the empty spot. A new empty spot is created. Continue
  • 17. 1 2 5 64 3 2 5 64 3 2 5 64 3 2 3 5 64 Heap property is preserved, but completeness is not preserved!
  • 18. DeleteMin 1. Copy the last number to the root (i.e. overwrite the minimum element stored there) 2. Restore the min-heap property by “bubble down”