Heap Sort
Heap Sort
TOPICS TO BE COVERED
• INTRODUCTION TO HEAPS
• ARRAY REPRESENTATION OF HEAPS
• HEAP TYPES
• ADDING/DELETING NODE FROM A HEAP
• MAINTAINING A HEAP PROPERTY
7 4
5 2 A heap is a binary tree that is filled in
Heap order
3
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)
5
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)
Heap Types
7
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)
Adding/Deleting Nodes
• New nodes are always inserted at the bottom level (left to
right)
• Nodes are removed from the bottom level (right to left)
8
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)
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
9
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)
12
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)
35 33 42 10 14 19 27 44 26 31
Max Heap
MAX-HEAPIFY(A, 2, 10)
A[2] A[4]
A[2] violates the heap property A[4] violates the heap property
A[4] A[9]
145,40,25,65,12,48,1,100,27,7,3,45,9,30
Construct Min Heap:
16
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)
Heapsort
• 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(Re heapify)
– Repeat this process until only one node remains
17
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)
Example..
Sort elements through heapsort (max heap)
15,20,7,9,30
81,89,9,11,14,76,54,22
References
1. Li`pschutz, Seymour, “Data Structures”, Schaum's Outline Series,
Tata McGraw Hill.
2. Data structure and algorithm by Narasimha Karumanchi.
3. www.tutorialspoint.com
4. www.geeksforgeeks.com
Books Recommended
• Goodrich, Michael T., Tamassia, Roberto, and Mount, David M.,
“Data Structures and Algorithms in C++”, Wiley Student Edition.
• Aho, Alfred V., Ullman, Jeffrey D., Hopcroft ,John E. “Data
Structures and Algorithms”, Addison Wesley
• Lipschutz, Seymour, “Data Structures”, Schaum's Outline Series,
Tata McGraw Hill.
• Gilberg/Forouzan,” Data Structure with C ,Cengage Learning.
• Augenstein,Moshe J , Tanenbaum, Aaron M, “Data Structures
using C and C++”, Prentice Hall of India