SlideShare a Scribd company logo
1 of 23
Heap
A heap is an array object that can be viewed as
a nearly complete binary tree.
3
5
2 4 1
6
6 5 3 2 4 1
1
2 3
4 5 6
1
2
Array Representation of Heaps
A heap can be stored as
an array A.
Root of tree is A[1]
Left child of A[i] = A[2i]
Right child of A[i] = A[2i + 1]
Parent of A[i] = A[ i/2 ]
3
Heap Types
Max-heaps (largest element at root), have
the max-heap property:
for all nodes i, excluding the root:
A[PARENT(i)] ≥ A[i]
Min-heaps (smallest element at root),
have the min-heap property:
for all nodes i, excluding the root:
A[PARENT(i)] ≤ A[i]
MAX HEAP
A complete binary tree called max heap ,if the
parent at any node is greater to the value of
each of its child nodes
Root nodes of max heap always the largest
values in tree.
Also called descending heap.
MIN HEAP
A complete binary tree called min heap ,if the
parent at any node is smaller to the value of
each of its child nodes
Root nodes of min heap always the smallest
values in tree.
Also called ascending heap.
What are Heaps Useful for?
To implement priority queues
Priority queue = a queue where all elements
have a “priority” associated with them
Remove in a priority queue removes the
element with the smallest priority
insert
removeMin
7
Operations on Heaps
Maintain/Restore the max-heap property
MAX-HEAPIFY
Create a max-heap from an unordered array
BUILD-MAX-HEAP
Sort an array in place
HEAPSORT
8
Maintaining the Heap Property
Suppose a node is smaller than a
child
Left and Right subtrees of i are max-heaps
To eliminate the violation:
Exchange with larger child
Move down the tree
Continue until node is not smaller than
children
9
Example: A 4 1 3 2 16 9 10 14 8 7
2
14 8
1
16
7
4
3
9 10
1
2 3
4 5 6 7
8 9 10
14
2 8
1
16
7
4
10
9 3
1
2 3
4 5 6 7
8 9 10
2
14 8
1
16
7
4
3
9 10
1
2 3
4 5 6 7
8 9 10
14
2 8
1
16
7
4
3
9 10
1
2 3
4 5 6 7
8 9 10
14
2 8
16
7
1
4
10
9 3
1
2 3
4 5 6 7
8 9 10
8
2 4
14
7
1
16
10
9 3
1
2 3
4 5 6 7
8 9 10
i = 5 i = 4 i = 3
i = 2 i = 1
Heap Removal
Remove element
from priority queues?
removeMin( )
Heap Removal
Begin downheap
Heap Removal
Heap Removal
Heap Removal
Terminate downheap when
reach leaf level
key parent is greater than key child
HEAP SORT ALGORITHM
HEAP SORT
a)Insmax heap( ) algorithm
b) Delmax Heap( ) algorithm
c) Heapsort( ) algorithm
16
Heap sort
Goal:
Sort an array using heap representations
Idea:
Build a max-heap from the array
Swap the root (the maximum element) with the last element
in the array
“Discard” this last node by decreasing the heap size
Call MAX-HEAPIFY on the new root
Repeat this process until only one node remains
HEAP SORT COMPLEXITY:- O(n log n)
InsMaxHeap (Tree, N, Item)
InsMaxHeap (Tree, N, Item)
A Heap H with N elements is stored in array Tree and Item of information is
given. Ptr gives location of Item as it rises in tree and Par denotes location of
parent of Item
1. Set N := N+1 and Ptr = N [Add new node to H and initialize Ptr]
2. [Find location to insert Item]
Repeat steps 3 to 6 while Ptr >1
3. Set Par := [Ptr/2] [Location of parent node]
4. If Item <= Tree[Par], then
Set Tree[Ptr] := Item and Return
[End of If structure]
5. Set Tree[Ptr] := Tree[Par] [Moves node down]
6. Set Ptr := Par [Updates Ptr]
[End of step 2 loop]
7. Set Tree[1] := Item [Assign Item as root of H]
8. Return
DelMaxHeap (Tree, N, Item)
A Heap H with N elements is stored in array Tree. Variable Last saves value of
original last node of H. Pointers Ptr, Left and Right give locations of Last and its
left & right children as Last sinks in tree.
1. Set Item := Tree[1] [Removes root of H]
2. Set Last := Tree[N] and N:=N-1 [Removes last node of H]
3. Set Ptr:= 1, Left:= 2 and Right:= 3 [Initializes pointers]
4. Repeat Steps 5 to 7 while Right <=N
5. If Last >= Tree[Left] and Last >= Tree[Right], then
Set Tree[Ptr] := Last and Return
[End of If structure]
6. If Tree[Right] <= Tree[Left], then
Set Tree[Ptr] := Tree[Left] and Ptr := Left
Else
Set Tree[Ptr] := Tree[Right] and Ptr := Right
[End of If structure]
7. Set Left := 2*Ptr and Right := Left +1
8. [End of Step 4 loop]
9. If Left = N and if Last < Tree[Left],
then Set Tree[PTR] = Tree[Left] and Ptr := Left
7. Set Tree[Ptr] := Last
8. Return
HEAP SORT ALGORITHM
HeapSort (A, N)
An array A with N elements is given. This algo. sorts elements of A.
1. [Build a Heap H]
Repeat for J=1 to N-1
Call InsHeap(A, J, A[J+1]) //InsHeap (Tree, N, Item)
[End of loop]
2. [Sort A by repeatedly deleting root of H]
Repeat while N>1
a) Call DelHeap(A, N, Item) //decreases N and returns Item
b) Set A[N+1] := Item
[End of loop]
3. Exit
20
Example: A=[7, 4, 3, 1, 2]
MAX-HEAPIFY(A, 1, 4) MAX-HEAPIFY(A, 1, 3) MAX-HEAPIFY(A, 1, 2)
MAX-HEAPIFY(A, 1, 1)
COMPLEXITY OF HEAP
Heap is a balanced binary tree, the height of the tree is  O(log n)
For the insert operation, we start by adding a value to the end of the
array  O(1) (assuming the array doesn't have to be expanded).
Then we swap values up the tree until the order property has been
restored  proportional to the height of the tree  O(log n)
For remove operation, we follow a path down the tree from the root to
a leaf  O(log n).
Heap sort Complexity:
a). To insert a single node in an empty heap is : O(1).
b). To insert a single element in a n node heap is : O(log n).
dd=time complexity for inserting one element=O(log n).
c.) To insert n elements in a n node heap is : O(n log n).
d.) To delete the largest element in a max heap tree : O(1).
e.) To delete the smallest element in a max heap tree :
O(log n).
f.) To delete n elements in a max heap tree : O(n log n).
g.) To create a heap, time complexity will be : O(n log n).
Now to sort the heap tree requires,
1. arrange or insert the elements in a form of heap i.e O(n log n) and
2. delete the elements one by one after swapping operation O(nlogn)
This gives Heap sort complexity = O(nlogn) + O(nlogn).
= 2 O(nlogn) = O(nlogn).
Polling Questions
On which algorithm is heap sort based on?
a) Fibonacci heap
b) Binary tree
c) Priority queue
d) FIFO

More Related Content

Similar to Unit III Heaps.ppt

Analysis of Algorithms-Heapsort
Analysis of Algorithms-HeapsortAnalysis of Algorithms-Heapsort
Analysis of Algorithms-HeapsortReetesh Gupta
 
Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Anand Ingle
 
21. Heap_new.ppt
21. Heap_new.ppt21. Heap_new.ppt
21. Heap_new.pptAryanGour1
 
Algorithm chapter 6
Algorithm chapter 6Algorithm chapter 6
Algorithm chapter 6chidabdu
 
presentation on b tress. heap trees.hashing
presentation on b tress. heap trees.hashingpresentation on b tress. heap trees.hashing
presentation on b tress. heap trees.hashingBindiya syed
 
Sienna 7 heaps
Sienna 7 heapsSienna 7 heaps
Sienna 7 heapschidabdu
 
heap sort in the design anad analysis of algorithms
heap sort in the design anad analysis of algorithmsheap sort in the design anad analysis of algorithms
heap sort in the design anad analysis of algorithmsssuser7319f8
 
Heap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithmsHeap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithmssamairaakram
 
Heap Sort Algorithm
Heap Sort Algorithm Heap Sort Algorithm
Heap Sort Algorithm Musaddiq Khan
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3infanciaj
 
05 heap 20161110_jintaeks
05 heap 20161110_jintaeks05 heap 20161110_jintaeks
05 heap 20161110_jintaeksJinTaek Seo
 

Similar to Unit III Heaps.ppt (20)

Cis435 week05
Cis435 week05Cis435 week05
Cis435 week05
 
Analysis of Algorithms-Heapsort
Analysis of Algorithms-HeapsortAnalysis of Algorithms-Heapsort
Analysis of Algorithms-Heapsort
 
Heapsort quick sort
Heapsort quick sortHeapsort quick sort
Heapsort quick sort
 
Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure
 
21. Heap_new.ppt
21. Heap_new.ppt21. Heap_new.ppt
21. Heap_new.ppt
 
Algorithms - "heap sort"
Algorithms - "heap sort"Algorithms - "heap sort"
Algorithms - "heap sort"
 
Heap
HeapHeap
Heap
 
Algorithm chapter 6
Algorithm chapter 6Algorithm chapter 6
Algorithm chapter 6
 
presentation on b tress. heap trees.hashing
presentation on b tress. heap trees.hashingpresentation on b tress. heap trees.hashing
presentation on b tress. heap trees.hashing
 
Sienna 7 heaps
Sienna 7 heapsSienna 7 heaps
Sienna 7 heaps
 
heap sort in the design anad analysis of algorithms
heap sort in the design anad analysis of algorithmsheap sort in the design anad analysis of algorithms
heap sort in the design anad analysis of algorithms
 
Heap tree
Heap treeHeap tree
Heap tree
 
Heap tree
Heap treeHeap tree
Heap tree
 
Heap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithmsHeap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithms
 
Heap Sort Algorithm
Heap Sort Algorithm Heap Sort Algorithm
Heap Sort Algorithm
 
Heap sort
Heap sortHeap sort
Heap sort
 
Sorting
SortingSorting
Sorting
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
 
05 heap 20161110_jintaeks
05 heap 20161110_jintaeks05 heap 20161110_jintaeks
05 heap 20161110_jintaeks
 
4 heapsort pq
4 heapsort pq4 heapsort pq
4 heapsort pq
 

More from RohitkumarYadav80

atm-facilities-and-equipment.pptx
atm-facilities-and-equipment.pptxatm-facilities-and-equipment.pptx
atm-facilities-and-equipment.pptxRohitkumarYadav80
 
1. Combinational Logic Circutis with examples (1).pdf
1. Combinational Logic Circutis with examples (1).pdf1. Combinational Logic Circutis with examples (1).pdf
1. Combinational Logic Circutis with examples (1).pdfRohitkumarYadav80
 
1. Combinational Logic Circutis with examples (1).pdf
1. Combinational Logic Circutis with examples (1).pdf1. Combinational Logic Circutis with examples (1).pdf
1. Combinational Logic Circutis with examples (1).pdfRohitkumarYadav80
 
JAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfJAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfRohitkumarYadav80
 

More from RohitkumarYadav80 (10)

1.pdf
1.pdf1.pdf
1.pdf
 
PEA305 workbook.pdf
PEA305 workbook.pdfPEA305 workbook.pdf
PEA305 workbook.pdf
 
atm-facilities-and-equipment.pptx
atm-facilities-and-equipment.pptxatm-facilities-and-equipment.pptx
atm-facilities-and-equipment.pptx
 
unit 1 MCQ 316.pdf
unit 1 MCQ 316.pdfunit 1 MCQ 316.pdf
unit 1 MCQ 316.pdf
 
1. Combinational Logic Circutis with examples (1).pdf
1. Combinational Logic Circutis with examples (1).pdf1. Combinational Logic Circutis with examples (1).pdf
1. Combinational Logic Circutis with examples (1).pdf
 
PEA305 Lec 0 1 (1).pptx
PEA305 Lec  0 1 (1).pptxPEA305 Lec  0 1 (1).pptx
PEA305 Lec 0 1 (1).pptx
 
7. CPU_Unit3 (1).pdf
7. CPU_Unit3 (1).pdf7. CPU_Unit3 (1).pdf
7. CPU_Unit3 (1).pdf
 
asymptotic_notations.pdf
asymptotic_notations.pdfasymptotic_notations.pdf
asymptotic_notations.pdf
 
1. Combinational Logic Circutis with examples (1).pdf
1. Combinational Logic Circutis with examples (1).pdf1. Combinational Logic Circutis with examples (1).pdf
1. Combinational Logic Circutis with examples (1).pdf
 
JAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfJAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdf
 

Recently uploaded

Fun all Day Call Girls in Erode { 9332606886 } VVIP NISHA Call Girls Near 5 S...
Fun all Day Call Girls in Erode { 9332606886 } VVIP NISHA Call Girls Near 5 S...Fun all Day Call Girls in Erode { 9332606886 } VVIP NISHA Call Girls Near 5 S...
Fun all Day Call Girls in Erode { 9332606886 } VVIP NISHA Call Girls Near 5 S...Sareena Khatun
 
Coastal Protection Measures in Hulhumale'
Coastal Protection Measures in Hulhumale'Coastal Protection Measures in Hulhumale'
Coastal Protection Measures in Hulhumale'NAP Global Network
 
An Atoll Futures Research Institute? Presentation for CANCC
An Atoll Futures Research Institute? Presentation for CANCCAn Atoll Futures Research Institute? Presentation for CANCC
An Atoll Futures Research Institute? Presentation for CANCCNAP Global Network
 
Time, Stress & Work Life Balance for Clerks with Beckie Whitehouse
Time, Stress & Work Life Balance for Clerks with Beckie WhitehouseTime, Stress & Work Life Balance for Clerks with Beckie Whitehouse
Time, Stress & Work Life Balance for Clerks with Beckie Whitehousesubs7
 
Delivery in 20 Mins Call Girls Malappuram { 9332606886 } VVIP NISHA Call Girl...
Delivery in 20 Mins Call Girls Malappuram { 9332606886 } VVIP NISHA Call Girl...Delivery in 20 Mins Call Girls Malappuram { 9332606886 } VVIP NISHA Call Girl...
Delivery in 20 Mins Call Girls Malappuram { 9332606886 } VVIP NISHA Call Girl...kumargunjan9515
 
Tuvalu Coastal Adaptation Project (TCAP)
Tuvalu Coastal Adaptation Project (TCAP)Tuvalu Coastal Adaptation Project (TCAP)
Tuvalu Coastal Adaptation Project (TCAP)NAP Global Network
 
Financing strategies for adaptation. Presentation for CANCC
Financing strategies for adaptation. Presentation for CANCCFinancing strategies for adaptation. Presentation for CANCC
Financing strategies for adaptation. Presentation for CANCCNAP Global Network
 
Contributi dei parlamentari del PD - Contributi L. 3/2019
Contributi dei parlamentari del PD - Contributi L. 3/2019Contributi dei parlamentari del PD - Contributi L. 3/2019
Contributi dei parlamentari del PD - Contributi L. 3/2019Partito democratico
 
Call Girls Umbergaon / 8250092165 Genuine Call girls with real Photos and Number
Call Girls Umbergaon / 8250092165 Genuine Call girls with real Photos and NumberCall Girls Umbergaon / 8250092165 Genuine Call girls with real Photos and Number
Call Girls Umbergaon / 8250092165 Genuine Call girls with real Photos and NumberSareena Khatun
 
Finance strategies for adaptation. Presentation for CANCC
Finance strategies for adaptation. Presentation for CANCCFinance strategies for adaptation. Presentation for CANCC
Finance strategies for adaptation. Presentation for CANCCNAP Global Network
 
PPT Item # 7&8 6900 Broadway P&Z Case # 438
PPT Item # 7&8 6900 Broadway P&Z Case # 438PPT Item # 7&8 6900 Broadway P&Z Case # 438
PPT Item # 7&8 6900 Broadway P&Z Case # 438ahcitycouncil
 
Lorain Road Business District Revitalization Plan Final Presentation
Lorain Road Business District Revitalization Plan Final PresentationLorain Road Business District Revitalization Plan Final Presentation
Lorain Road Business District Revitalization Plan Final PresentationCuyahoga County Planning Commission
 
Call Girl Service in Korba 9332606886 High Profile Call Girls You Can Get ...
Call Girl Service in Korba   9332606886  High Profile Call Girls You Can Get ...Call Girl Service in Korba   9332606886  High Profile Call Girls You Can Get ...
Call Girl Service in Korba 9332606886 High Profile Call Girls You Can Get ...kumargunjan9515
 
Call Girls Koregaon Park - 8250092165 Our call girls are sure to provide you ...
Call Girls Koregaon Park - 8250092165 Our call girls are sure to provide you ...Call Girls Koregaon Park - 8250092165 Our call girls are sure to provide you ...
Call Girls Koregaon Park - 8250092165 Our call girls are sure to provide you ...Sareena Khatun
 
Managing large-scale outbreaks at Farrow-to-Weaner Farms
Managing large-scale outbreaks at Farrow-to-Weaner FarmsManaging large-scale outbreaks at Farrow-to-Weaner Farms
Managing large-scale outbreaks at Farrow-to-Weaner FarmsHarm Kiezebrink
 
Premium Prayagraj ❤️🍑 6378878445 👄🫦Independent Escort Service
Premium  Prayagraj ❤️🍑 6378878445 👄🫦Independent Escort ServicePremium  Prayagraj ❤️🍑 6378878445 👄🫦Independent Escort Service
Premium Prayagraj ❤️🍑 6378878445 👄🫦Independent Escort Servicevershagrag
 

Recently uploaded (20)

Fun all Day Call Girls in Erode { 9332606886 } VVIP NISHA Call Girls Near 5 S...
Fun all Day Call Girls in Erode { 9332606886 } VVIP NISHA Call Girls Near 5 S...Fun all Day Call Girls in Erode { 9332606886 } VVIP NISHA Call Girls Near 5 S...
Fun all Day Call Girls in Erode { 9332606886 } VVIP NISHA Call Girls Near 5 S...
 
Coastal Protection Measures in Hulhumale'
Coastal Protection Measures in Hulhumale'Coastal Protection Measures in Hulhumale'
Coastal Protection Measures in Hulhumale'
 
An Atoll Futures Research Institute? Presentation for CANCC
An Atoll Futures Research Institute? Presentation for CANCCAn Atoll Futures Research Institute? Presentation for CANCC
An Atoll Futures Research Institute? Presentation for CANCC
 
Time, Stress & Work Life Balance for Clerks with Beckie Whitehouse
Time, Stress & Work Life Balance for Clerks with Beckie WhitehouseTime, Stress & Work Life Balance for Clerks with Beckie Whitehouse
Time, Stress & Work Life Balance for Clerks with Beckie Whitehouse
 
The Outlook for the Budget and the Economy
The Outlook for the Budget and the EconomyThe Outlook for the Budget and the Economy
The Outlook for the Budget and the Economy
 
Sustainability by Design: Assessment Tool for Just Energy Transition Plans
Sustainability by Design: Assessment Tool for Just Energy Transition PlansSustainability by Design: Assessment Tool for Just Energy Transition Plans
Sustainability by Design: Assessment Tool for Just Energy Transition Plans
 
Delivery in 20 Mins Call Girls Malappuram { 9332606886 } VVIP NISHA Call Girl...
Delivery in 20 Mins Call Girls Malappuram { 9332606886 } VVIP NISHA Call Girl...Delivery in 20 Mins Call Girls Malappuram { 9332606886 } VVIP NISHA Call Girl...
Delivery in 20 Mins Call Girls Malappuram { 9332606886 } VVIP NISHA Call Girl...
 
Tuvalu Coastal Adaptation Project (TCAP)
Tuvalu Coastal Adaptation Project (TCAP)Tuvalu Coastal Adaptation Project (TCAP)
Tuvalu Coastal Adaptation Project (TCAP)
 
Financing strategies for adaptation. Presentation for CANCC
Financing strategies for adaptation. Presentation for CANCCFinancing strategies for adaptation. Presentation for CANCC
Financing strategies for adaptation. Presentation for CANCC
 
AHMR volume 10 number 1 January-April 2024
AHMR volume 10 number 1 January-April 2024AHMR volume 10 number 1 January-April 2024
AHMR volume 10 number 1 January-April 2024
 
Contributi dei parlamentari del PD - Contributi L. 3/2019
Contributi dei parlamentari del PD - Contributi L. 3/2019Contributi dei parlamentari del PD - Contributi L. 3/2019
Contributi dei parlamentari del PD - Contributi L. 3/2019
 
Call Girls Umbergaon / 8250092165 Genuine Call girls with real Photos and Number
Call Girls Umbergaon / 8250092165 Genuine Call girls with real Photos and NumberCall Girls Umbergaon / 8250092165 Genuine Call girls with real Photos and Number
Call Girls Umbergaon / 8250092165 Genuine Call girls with real Photos and Number
 
Finance strategies for adaptation. Presentation for CANCC
Finance strategies for adaptation. Presentation for CANCCFinance strategies for adaptation. Presentation for CANCC
Finance strategies for adaptation. Presentation for CANCC
 
PPT Item # 7&8 6900 Broadway P&Z Case # 438
PPT Item # 7&8 6900 Broadway P&Z Case # 438PPT Item # 7&8 6900 Broadway P&Z Case # 438
PPT Item # 7&8 6900 Broadway P&Z Case # 438
 
Lorain Road Business District Revitalization Plan Final Presentation
Lorain Road Business District Revitalization Plan Final PresentationLorain Road Business District Revitalization Plan Final Presentation
Lorain Road Business District Revitalization Plan Final Presentation
 
BioandPicforRepKendrick_LastUpdatedMay2024
BioandPicforRepKendrick_LastUpdatedMay2024BioandPicforRepKendrick_LastUpdatedMay2024
BioandPicforRepKendrick_LastUpdatedMay2024
 
Call Girl Service in Korba 9332606886 High Profile Call Girls You Can Get ...
Call Girl Service in Korba   9332606886  High Profile Call Girls You Can Get ...Call Girl Service in Korba   9332606886  High Profile Call Girls You Can Get ...
Call Girl Service in Korba 9332606886 High Profile Call Girls You Can Get ...
 
Call Girls Koregaon Park - 8250092165 Our call girls are sure to provide you ...
Call Girls Koregaon Park - 8250092165 Our call girls are sure to provide you ...Call Girls Koregaon Park - 8250092165 Our call girls are sure to provide you ...
Call Girls Koregaon Park - 8250092165 Our call girls are sure to provide you ...
 
Managing large-scale outbreaks at Farrow-to-Weaner Farms
Managing large-scale outbreaks at Farrow-to-Weaner FarmsManaging large-scale outbreaks at Farrow-to-Weaner Farms
Managing large-scale outbreaks at Farrow-to-Weaner Farms
 
Premium Prayagraj ❤️🍑 6378878445 👄🫦Independent Escort Service
Premium  Prayagraj ❤️🍑 6378878445 👄🫦Independent Escort ServicePremium  Prayagraj ❤️🍑 6378878445 👄🫦Independent Escort Service
Premium Prayagraj ❤️🍑 6378878445 👄🫦Independent Escort Service
 

Unit III Heaps.ppt

  • 1. Heap A heap is an array object that can be viewed as a nearly complete binary tree. 3 5 2 4 1 6 6 5 3 2 4 1 1 2 3 4 5 6 1
  • 2. 2 Array Representation of Heaps A heap can be stored as an array A. Root of tree is A[1] Left child of A[i] = A[2i] Right child of A[i] = A[2i + 1] Parent of A[i] = A[ i/2 ]
  • 3. 3 Heap Types Max-heaps (largest element at root), have the max-heap property: for all nodes i, excluding the root: A[PARENT(i)] ≥ A[i] Min-heaps (smallest element at root), have the min-heap property: for all nodes i, excluding the root: A[PARENT(i)] ≤ A[i]
  • 4. MAX HEAP A complete binary tree called max heap ,if the parent at any node is greater to the value of each of its child nodes Root nodes of max heap always the largest values in tree. Also called descending heap.
  • 5. MIN HEAP A complete binary tree called min heap ,if the parent at any node is smaller to the value of each of its child nodes Root nodes of min heap always the smallest values in tree. Also called ascending heap.
  • 6. What are Heaps Useful for? To implement priority queues Priority queue = a queue where all elements have a “priority” associated with them Remove in a priority queue removes the element with the smallest priority insert removeMin
  • 7. 7 Operations on Heaps Maintain/Restore the max-heap property MAX-HEAPIFY Create a max-heap from an unordered array BUILD-MAX-HEAP Sort an array in place HEAPSORT
  • 8. 8 Maintaining the Heap Property Suppose a node is smaller than a child Left and Right subtrees of i are max-heaps To eliminate the violation: Exchange with larger child Move down the tree Continue until node is not smaller than children
  • 9. 9 Example: A 4 1 3 2 16 9 10 14 8 7 2 14 8 1 16 7 4 3 9 10 1 2 3 4 5 6 7 8 9 10 14 2 8 1 16 7 4 10 9 3 1 2 3 4 5 6 7 8 9 10 2 14 8 1 16 7 4 3 9 10 1 2 3 4 5 6 7 8 9 10 14 2 8 1 16 7 4 3 9 10 1 2 3 4 5 6 7 8 9 10 14 2 8 16 7 1 4 10 9 3 1 2 3 4 5 6 7 8 9 10 8 2 4 14 7 1 16 10 9 3 1 2 3 4 5 6 7 8 9 10 i = 5 i = 4 i = 3 i = 2 i = 1
  • 10. Heap Removal Remove element from priority queues? removeMin( )
  • 14. Heap Removal Terminate downheap when reach leaf level key parent is greater than key child
  • 15. HEAP SORT ALGORITHM HEAP SORT a)Insmax heap( ) algorithm b) Delmax Heap( ) algorithm c) Heapsort( ) algorithm
  • 16. 16 Heap sort Goal: Sort an array using heap representations Idea: Build a max-heap from the array Swap the root (the maximum element) with the last element in the array “Discard” this last node by decreasing the heap size Call MAX-HEAPIFY on the new root Repeat this process until only one node remains HEAP SORT COMPLEXITY:- O(n log n)
  • 17. InsMaxHeap (Tree, N, Item) InsMaxHeap (Tree, N, Item) A Heap H with N elements is stored in array Tree and Item of information is given. Ptr gives location of Item as it rises in tree and Par denotes location of parent of Item 1. Set N := N+1 and Ptr = N [Add new node to H and initialize Ptr] 2. [Find location to insert Item] Repeat steps 3 to 6 while Ptr >1 3. Set Par := [Ptr/2] [Location of parent node] 4. If Item <= Tree[Par], then Set Tree[Ptr] := Item and Return [End of If structure] 5. Set Tree[Ptr] := Tree[Par] [Moves node down] 6. Set Ptr := Par [Updates Ptr] [End of step 2 loop] 7. Set Tree[1] := Item [Assign Item as root of H] 8. Return
  • 18. DelMaxHeap (Tree, N, Item) A Heap H with N elements is stored in array Tree. Variable Last saves value of original last node of H. Pointers Ptr, Left and Right give locations of Last and its left & right children as Last sinks in tree. 1. Set Item := Tree[1] [Removes root of H] 2. Set Last := Tree[N] and N:=N-1 [Removes last node of H] 3. Set Ptr:= 1, Left:= 2 and Right:= 3 [Initializes pointers] 4. Repeat Steps 5 to 7 while Right <=N 5. If Last >= Tree[Left] and Last >= Tree[Right], then Set Tree[Ptr] := Last and Return [End of If structure] 6. If Tree[Right] <= Tree[Left], then Set Tree[Ptr] := Tree[Left] and Ptr := Left Else Set Tree[Ptr] := Tree[Right] and Ptr := Right [End of If structure] 7. Set Left := 2*Ptr and Right := Left +1 8. [End of Step 4 loop] 9. If Left = N and if Last < Tree[Left], then Set Tree[PTR] = Tree[Left] and Ptr := Left 7. Set Tree[Ptr] := Last 8. Return
  • 19. HEAP SORT ALGORITHM HeapSort (A, N) An array A with N elements is given. This algo. sorts elements of A. 1. [Build a Heap H] Repeat for J=1 to N-1 Call InsHeap(A, J, A[J+1]) //InsHeap (Tree, N, Item) [End of loop] 2. [Sort A by repeatedly deleting root of H] Repeat while N>1 a) Call DelHeap(A, N, Item) //decreases N and returns Item b) Set A[N+1] := Item [End of loop] 3. Exit
  • 20. 20 Example: A=[7, 4, 3, 1, 2] MAX-HEAPIFY(A, 1, 4) MAX-HEAPIFY(A, 1, 3) MAX-HEAPIFY(A, 1, 2) MAX-HEAPIFY(A, 1, 1)
  • 21. COMPLEXITY OF HEAP Heap is a balanced binary tree, the height of the tree is  O(log n) For the insert operation, we start by adding a value to the end of the array  O(1) (assuming the array doesn't have to be expanded). Then we swap values up the tree until the order property has been restored  proportional to the height of the tree  O(log n) For remove operation, we follow a path down the tree from the root to a leaf  O(log n).
  • 22. Heap sort Complexity: a). To insert a single node in an empty heap is : O(1). b). To insert a single element in a n node heap is : O(log n). dd=time complexity for inserting one element=O(log n). c.) To insert n elements in a n node heap is : O(n log n). d.) To delete the largest element in a max heap tree : O(1). e.) To delete the smallest element in a max heap tree : O(log n). f.) To delete n elements in a max heap tree : O(n log n). g.) To create a heap, time complexity will be : O(n log n). Now to sort the heap tree requires, 1. arrange or insert the elements in a form of heap i.e O(n log n) and 2. delete the elements one by one after swapping operation O(nlogn) This gives Heap sort complexity = O(nlogn) + O(nlogn). = 2 O(nlogn) = O(nlogn).
  • 23. Polling Questions On which algorithm is heap sort based on? a) Fibonacci heap b) Binary tree c) Priority queue d) FIFO