Introduction To Heap Sort
Introduction To Heap Sort
by Lenny Lewis
Understanding Heaps
Binary Heap Max Heap Array Representation
A binary heap is a complete binary The root node is always the largest For a node at index `i`, the left
tree. It can be represented as an element. Every node's value is child is `2*i + 1`, the right child is
array. Two types: Max Heap and greater than or equal to its `2*i + 2`, and the parent is `(i - 1) /
Min Heap. children's values. 2`.
Building the Max Heap
Heapify
Maintains the max heap property. Start from the last non-
leaf node. Compare the node with its children.
Swap
If the node is smaller than either child, swap it with the
larger child.
Recursively Heapify
Recursively heapify the affected sub-tree.
Build Heap
Start from the middle of the array and go backwards. For
each node, call heapify.
Heap Sort: Sorting Phase
1
Swap Root
Heapify Root
3
Repeatedly extract the maximum element from the heap. Then place it at the end of the sorted array.
Swap the root with the last element. Reduce heap size. Heapify the root. Repeat until size is 1.
Detailed Example (Part 1)
3 Resulting Heap
[16, 14, 10, 8, 7, 9, 3, 2, 4, 1]
Detailed Example (Part 2)
Sorted Array
Resulting Heap
Heapify Root
Swap 16 with 7
Continue sorting. Swap 16 with 7: [7, 14, 10, 8, 4, 9, 3, 2, 4, 16]. Heapify the root node (7). The sorted portion grows.
Complexity Analysis
Building Heap O(n)
Space O(1)
Building the heap takes O(n) time. Sorting takes O(n log n) time.
The overall time complexity is O(n log n). It sorts in place with O(1)
space complexity.
Applications and
Conclusion