Heap sort is a sorting method on Binary Heap.
First things First
All you need to know about heap.
- Heap must be a Complete Binary Tree
- All trees are either Min Heap or Max Heap
- Heap sort is an in-place sort algorithm
- It is not very stable
Here I plan to construct Heap Sort Algorithm on a Min Heap.The Algorithm primarily has two main functions.
- Heapify Function
- Heap Sort Function
References from CLRS
Parent(i) 1 return(floor(i/2))
Left (i) 1 return ( 2 * i + 1 )
Right (i) 1 return ( 2 * i + 2 )
Property for Max Heap
A[ Parent ] >= A[ i ]
Property for Min Heap
A[ Parent ] <= A[ i ]
Heapify Function
Heap Sort Function
Worst Case Time Complexity : O(n log n)
Space Complexity : O(n)
Source Code: HeapSort.cpp
References: StudyTonight