2.7 Heaps
2.7 Heaps
UNIVERSITY INSTITUTE OF
ENGINEERING
COMPUTER SCIENCE ENGINEERING
Bachelor of Engineering
Design and Analysis of
Algorithms(CSH-311/ITH-311)
Heaps (CO2)
Outcome:
• Student will understand
Heap and its types
Heap sort
POLL Question
a) Leaf node
b) First node of left sub tree
c) root node
d) First node of right sub tree
Heap
Building a heap
Heap Sort
• Heaps can be used in sorting an array. In max-heaps, maximum
element will always be at the root. Heap Sort uses this
property of heap to sort the array.
• Consider an array Arr which is to be sorted using Heap Sort.
1. Initially build a max heap of elements in Arr.
2. The root element, that is Arr[1], will contain maximum
element of Arr. After that, swap this element with the last
element of Arr and heapify the max heap excluding the last
element which is already in its correct position and then
decrease the length of heap by one.
3. Repeat the step 2, until all the elements are in their correct
position
Example:
Example (Contd.)
REFERENCES
Text books:
•Cormen, Leiserson, Rivest, Stein, “Introduction to Algorithms”, Prentice Hall of
India, 3rd edition 2012. problem, Graph coloring.
•Horowitz, Sahni and Rajasekaran, “Fundamentals of ComputerAlgorithms”,
University Press (India), 2nd edition
Websites:
1.https://www.tutorialspoint.com/data_structures_algorithms/
heap_data_structure.htm
2.https://www.geeksforgeeks.org/
Summary
Introduction to Heaps
• Basic terms
Types of Heaps
• Max-heap
• Min-heap
• Heap Sort