Basic programming - Heap Sort
Approach:
Heap is a complete binary tree. And, heap feature is that parent node must bigger than its child nodes. It also calls max-heap.
So, heapify() function ensures the max-heap principle. Get the index of left/right child easily by using the argument i
(parent node). Then, find the child nodes which is bigger than their parent node and call swap().
If all of the elements are no heap priciple, heapify() function is not enough handling, so we need to write buildheap() function at the begining.
Buildheap() function scans all of the elements between parent node and child nodes and forms a max-heap.
Finally, we need to implement heap sort. We can always pop the root node because it is a largest element. Hence, use swap(arr, 0, i)
to put root node to the tail of array. i
is the the size of arrary - 1 and it will descending. Then, call heapify() function to make larger element moved to root and call swap() again until i
is equal to zero.
Space complexity: O(1)
Stable/Unstable: Stable
Source code
Version 1
1 |
|