Heap Sort Min-Heap or Max-Heap
Heap Sort Min-Heap or Max-Heap
Since heappify uses recursion, it can be difficult to grasp. So let's first think about
how you would heapify a tree with just three elements.
heapify(array)
Root = array[0]
Largest = max( array[0] , array [2*0 + 1], array[2*0+2])
if(Root != Largest)
Swap(Root, Largest)
How to heapify root element when its subtrees are already max heaps ?
The top element isn't a max-heap but all the sub-trees are max-heaps.
To maintain the max-heap property for the entire tree, we will have to keep pushing 2 downwards until it reaches its
correct position.
(a) Heap
1.Since the tree satisfies Max-Heap property, then the largest element
is stored at the root node.
2.Swap: Remove the root element and put at the end of the array
(at nth position) Put the last element of the tree (heap) at the vacant
place.
4.Heapify: Heapify the root element again so that we have the largest
element at root.
5.The process is repeated until all the items of the list are sorted.
•Best Case Complexity - It occurs when there is no sorting required, i.e. the
array is already sorted. The best-case time complexity of heap sort is O(n logn).
•Average Case Complexity - It occurs when the array elements are in jumbled
order that is not properly ascending and not properly descending. The average
case time complexity of heap sort is O(n log n).
•Worst Case Complexity - It occurs when the array elements are required to be
sorted in reverse order. That means suppose you have to sort the array elements
in ascending order, but its elements are in descending order. The worst-case
time complexity of heap sort is O(n log n).
The time complexity of heap sort is O(n logn) in all three cases (best case,
average case, and worst case). The height of a complete binary tree having n
elements is logn.