Heap sort is a comparison-based sorting technique based on a Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for the remaining elements.
Basic Concepts
- Binary Heap: A complete binary tree which satisfies the heap ordering property.
- Max Heap: The value of each node is greater than or equal to the values of its children.
- Min Heap: The value of each node is less than or equal to the values of its children.
Steps
- Build a Max Heap from the input data.
- At this point, the largest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of the heap by 1. Finally, heapify the root of the tree.
- Repeat step 2 while the size of the heap is greater than 1.
Example
Let's sort the array [12, 11, 13, 5, 6, 7]
using heap sort.
- Build a max heap:
[13, 12, 7, 5, 6, 11]
- Replace the root with the last item:
[5, 12, 7, 13, 6, 11]
- Heapify the root:
[7, 12, 5, 13, 6, 11]
- Replace the root with the last item:
[5, 7, 5, 13, 6, 11]
- Heapify the root:
[5, 7, 5, 6, 13, 11]
- Replace the root with the last item:
[5, 7, 5, 6, 11, 13]
- Heapify the root:
[5, 7, 5, 6, 11, 13]
The sorted array is [5, 7, 5, 6, 11, 13]
.
Resources
For more information on heap sort, you can refer to our Heap Sort Advanced Tutorial.
Heap Sort Visualization