Heap Sort in C++
1. What Is Heap Sort?
Heap Sort is a sorting technique based on a special tree-based data structure called a heap.
A heap is a complete binary tree that follows a specific ordering property. Heap Sort commonly uses a Max Heap to sort an array in ascending order.
In a Max Heap, every parent node is greater than or equal to its children. Therefore, the largest element is always available at the root.
Example
Consider the following array:
arr = {4, 10, 3, 5, 1}
After applying Heap Sort:
arr = {1, 3, 4, 5, 10}
2. What Is a Heap?
A heap is a complete binary tree that satisfies the heap property.
A complete binary tree is a binary tree in which every level is completely filled except possibly the last level, and nodes at the last level are filled from left to right.
Types of Heap
Max Heap
In a Max Heap, the value of every parent node is greater than or equal to the values of its children.
50
/ \
30 40
/ \
10 20
The largest element is present at the root.
Min Heap
In a Min Heap, the value of every parent node is smaller than or equal to the values of its children.
10
/ \
20 15
/ \
40 30
The smallest element is present at the root.
3. Array Representation of a Heap
A complete binary tree can be stored efficiently in an array. No separate tree nodes or pointers are required.
For a zero-based array, the relationships between a node and its children are:
- Parent index: (i - 1) / 2
- Left child index: 2 * i + 1
- Right child index: 2 * i + 2
Example
Array: {50, 30, 40, 10, 20}
The corresponding tree is:
50
/ \
30 40
/ \
10 20
| Index | Value | Left Child Index | Right Child Index |
|---|---|---|---|
| 0 | 50 | 1 | 2 |
| 1 | 30 | 3 | 4 |
| 2 | 40 | 5 | 6 |
| 3 | 10 | 7 | 8 |
| 4 | 20 | 9 | 10 |
4. What Is Heapify?
Heapify is the process of restoring the heap property in a subtree.
For a Max Heap, the parent must be greater than or equal to its children. If this property is violated, we compare the parent with its children and move the largest value upward.
Heapify Steps
- Start from a node whose subtree may violate the Max Heap property.
- Assume the current node is the largest.
- Compare it with its left child.
- Compare it with its right child.
- Find the largest among the current node and its children.
- If a child is larger, swap it with the current node.
- Continue heapifying the affected subtree.
Example
10
/ \
30 20
The parent 10 is smaller than its largest child 30. Swap them.
30
/ \
10 20
The Max Heap property is now satisfied.
5. Heapify Function in C++
The following function maintains the Max Heap property for the subtree rooted at index i.
void heapify(vector<int>& arr, int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest]) {
largest = left;
}
if (right < n && arr[right] > arr[largest]) {
largest = right;
}
if (largest != i) {
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
Code Explanation
- largest = i: Initially assume the current node is the largest.
- left = 2 * i + 1: Calculate the left child index.
- right = 2 * i + 2: Calculate the right child index.
- left < n: Check whether the left child exists.
- right < n: Check whether the right child exists.
- swap(): Move the largest value to the parent position.
- Recursive heapify: Restore the heap property in the affected subtree.
6. How Does Heap Sort Work?
Heap Sort works in two main phases:
Phase 1: Build a Max Heap
Convert the input array into a Max Heap. The largest element will be at index 0.
Phase 2: Extract the Maximum Element
- Swap the root element with the last element in the active heap.
- Reduce the heap size by one.
- Apply heapify to the root to restore the Max Heap property.
- Repeat until only one element remains in the heap.
7. Step-by-Step Example of Heap Sort
Consider the following array:
arr = {4, 10, 3, 5, 1}
Step 1: Build a Max Heap
After applying heapify from the last non-leaf node toward the root, the array becomes:
{10, 5, 3, 4, 1}
Its tree representation is:
10
/ \
5 3
/ \
4 1
Step 2: Move the Largest Element to the End
Swap the root 10 with the last element 1.
{1, 5, 3, 4, 10}
The element 10 is now in its final sorted position. Reduce the heap size and heapify the remaining elements.
{5, 4, 3, 1, 10}
Step 3: Extract the Next Largest Element
Swap 5 with the last element in the active heap.
{1, 4, 3, 5, 10}
After heapify:
{4, 1, 3, 5, 10}
Step 4: Continue Extraction
Move 4 to its final position and heapify again:
{3, 1, 4, 5, 10}
Then move 3 to its final position:
{1, 3, 4, 5, 10}
Final Sorted Array: 1 3 4 5 10
8. Complete Heap Sort Algorithm
The Heap Sort algorithm first builds a Max Heap and then repeatedly extracts the maximum element.
Pseudocode
heapSort(arr, n):
for i = n / 2 - 1 down to 0:
heapify(arr, n, i)
for i = n - 1 down to 1:
swap arr[0] and arr[i]
heapify(arr, i, 0)
9. Complete C++ Program for Heap Sort
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void heapify(vector<int>& arr, int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest]) {
largest = left;
}
if (right < n && arr[right] > arr[largest]) {
largest = right;
}
if (largest != i) {
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
void heapSort(vector<int>& arr) {
int n = arr.size();
// Build Max Heap
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
// Extract elements one by one
for (int i = n - 1; i > 0; i--) {
swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}
int main() {
vector<int> arr = {4, 10, 3, 5, 1};
heapSort(arr);
cout << "Sorted Array: ";
for (int x : arr) {
cout << x << " ";
}
return 0;
}
Output
Sorted Array: 1 3 4 5 10
10. Understanding the Complete Code
Building the Max Heap
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
All nodes after index n / 2 - 1 are leaf nodes in a zero-based array representation. Leaf nodes already satisfy the heap property.
Therefore, heap construction begins at the last non-leaf node and moves backward toward the root.
Swapping the Root with the Last Element
swap(arr[0], arr[i]);
The root contains the largest value. Swapping it with the last element of the active heap places it in its final sorted position.
Reducing the Heap Size
heapify(arr, i, 0);
Passing i as the new heap size excludes the element that has already been placed at the end of the array.
11. Dry Run of Heap Sort
Input:
arr = {6, 4, 8, 2, 1}
Build Max Heap
{8, 4, 6, 2, 1}
Extraction Process
| Operation | Array |
|---|---|
| Initial Max Heap | 8, 4, 6, 2, 1 |
| Move 8 to end and heapify | 6, 4, 1, 2, 8 |
| Move 6 to end and heapify | 4, 2, 1, 6, 8 |
| Move 4 to end and heapify | 2, 1, 4, 6, 8 |
| Move 2 to end | 1, 2, 4, 6, 8 |
Sorted Array: 1 2 4 6 8
12. Time Complexity of Heap Sort
Heap Sort has O(n log n) time complexity in all three standard cases.
Building the Heap
Building a heap using bottom-up heap construction takes O(n) time, not O(n log n).
Extracting Elements
Each extraction requires O(log n) time to restore the heap property. Since there are approximately n extractions, this phase takes O(n log n).
Total Time Complexity
O(n) + O(n log n) = O(n log n)
| Case | Time Complexity |
|---|---|
| Best Case | O(n log n) |
| Average Case | O(n log n) |
| Worst Case | O(n log n) |
13. Space Complexity of Heap Sort
The standard implementation rearranges elements inside the original array. It does not need another array proportional to the input size.
The recursive heapify implementation uses a recursion stack of O(log n) in the worst case because the height of a binary heap is O(log n).
An iterative heapify implementation can reduce auxiliary space to O(1).
Recursive Heapify: O(log n) auxiliary stack space
Iterative Heapify: O(1) auxiliary space
14. Heap Sort Complexity Summary
| Operation | Time Complexity |
|---|---|
| Build Max Heap | O(n) |
| One Heapify Operation | O(log n) |
| Extract Maximum | O(log n) |
| Complete Heap Sort | O(n log n) |
| Recursive Auxiliary Space | O(log n) |
| Iterative Auxiliary Space | O(1) |
15. Properties of Heap Sort
| Property | Description |
|---|---|
| Algorithm Type | Comparison-based sorting |
| Data Structure | Binary Heap |
| Technique | Heap-based sorting |
| Best Time | O(n log n) |
| Average Time | O(n log n) |
| Worst Time | O(n log n) |
| Stable | No, standard implementation |
| In-place | Yes, for the iterative implementation |
16. Is Heap Sort Stable?
Standard Heap Sort is not stable. During heap construction and extraction, elements with equal values may be swapped in ways that change their original relative order.
17. Is Heap Sort In-place?
Heap Sort is generally considered an in-place sorting algorithm because it rearranges elements within the original array.
The iterative version of heapify uses O(1) auxiliary space. The recursive version uses additional recursion stack space.
18. Advantages of Heap Sort
- Guarantees O(n log n) time complexity in all cases.
- Does not require a separate array proportional to the input size.
- Works efficiently with large arrays.
- Does not depend on choosing a pivot.
- Has predictable worst-case performance.
19. Disadvantages of Heap Sort
- Standard Heap Sort is not stable.
- Often has poorer cache locality than algorithms such as Quick Sort.
- Heap operations can involve many comparisons and swaps.
- Its implementation may be less intuitive for beginners.
20. Applications of Heap Sort and Heaps
- Sorting arrays when guaranteed O(n log n) performance is required.
- Priority queue implementations.
- Finding the largest or smallest elements.
- Scheduling tasks based on priority.
- Problems involving repeated maximum or minimum extraction.
- Building efficient selection algorithms.
21. Heap Sort vs Quick Sort vs Merge Sort
| Feature | Heap Sort | Quick Sort | Merge Sort |
|---|---|---|---|
| Best Time | O(n log n) | O(n log n) | O(n log n) |
| Average Time | O(n log n) | O(n log n) | O(n log n) |
| Worst Time | O(n log n) | O(n²) | O(n log n) |
| Auxiliary Space | O(1) iterative heapify | O(log n) average stack | O(n) for standard array implementation |
| Stable | No | No | Yes, standard implementation |
| Technique | Heap-based | Divide and Conquer | Divide and Conquer |
22. Common Mistakes in Heap Sort
- Incorrect child indexes: For zero-based indexing, use 2 * i + 1 and 2 * i + 2.
- Incorrect starting index: Start heap construction from n / 2 - 1.
- Incorrect heap size: After moving the maximum to the end, reduce the active heap size.
- Incorrect heapify comparison: Compare the parent with both existing children.
- Heapifying the wrong subtree: After swapping, continue heapifying from the child's new position.
- Confusing Max Heap and Min Heap: Use a Max Heap for the standard ascending-order implementation described here.
23. Interview Questions
- What is Heap Sort?
- What is a binary heap?
- What is the difference between a Max Heap and a Min Heap?
- What is heapify?
- How is a heap represented in an array?
- What are the formulas for finding parent and child indexes?
- Why does Heap Sort use a Max Heap for ascending order?
- What is the time complexity of building a heap?
- Why does building a heap take O(n) time?
- What is the time complexity of Heap Sort?
- Is Heap Sort stable?
- Is Heap Sort in-place?
- What is the space complexity of recursive heapify?
- How is Heap Sort different from Quick Sort?
- What are the practical applications of heaps?
24. Practice Problems
Problem 1: Sort an Array Using Heap Sort
Given an integer array, sort it in ascending order using Heap Sort.
Input:
{4, 10, 3, 5, 1}
Output:
{1, 3, 4, 5, 10}
Problem 2: Build a Max Heap
Convert the given array into a valid Max Heap.
Input:
{3, 9, 2, 1, 4, 5}
One Valid Max Heap:
{9, 4, 5, 1, 3, 2}
Problem 3: Build a Min Heap
Modify the heapify logic to construct a Min Heap.
Input:
{8, 4, 7, 1, 3, 9}
One Valid Min Heap:
{1, 3, 7, 8, 4, 9}
Problem 4: Find the Kth Largest Element
Given an array and an integer k, find the kth largest element using a heap.
Input:
arr = {3, 2, 1, 5, 6, 4}
k = 2
Output:
5
Problem 5: Implement Iterative Heapify
Rewrite the recursive heapify function using a loop instead of recursive calls.
Input:
{10, 20, 15, 30, 40}
Task:
Restore the Max Heap property iteratively.
25. Summary
- Heap Sort is a comparison-based sorting algorithm.
- It uses a Binary Heap data structure.
- A Max Heap is used for ascending-order sorting.
- Heapify restores the heap property.
- Building a heap takes O(n) time.
- Each extraction takes O(log n) time.
- Best, average, and worst-case time complexity is O(n log n).
- Standard Heap Sort is not stable.
- Iterative Heap Sort can use O(1) auxiliary space.