Heap Sort in C++
Sort an array with heap sort in C++ by building a max heap and repeatedly moving the root to the end. Explains child index formulas 2i + 1 and 2i + 2 and heapify.
1#include <iostream>2using namespace std;34void heapify(int arr[], int n, int i) {5 int largest = i;6 int left = 2 * i + 1;7 int right = 2 * i + 2;89 if (left < n && arr[left] > arr[largest])10 largest = left;1112 if (right < n && arr[right] > arr[largest])13 largest = right;1415 if (largest != i) {16 swap(arr[i], arr[largest]);17 heapify(arr, n, largest);18 }19}2021void heapSort(int arr[], int n) {22 // Build max heap23 for (int i = n / 2 - 1; i >= 0; i--)24 heapify(arr, n, i);2526 // Extract elements from heap one by one27 for (int i = n - 1; i > 0; i--) {28 swap(arr[0], arr[i]);29 heapify(arr, i, 0);30 }31}3233void printArray(int arr[], int n) {34 for (int i = 0; i < n; i++) {35 cout << arr[i] << " ";36 }37 cout << endl;38}3940int main() {41 int arr[] = {64, 34, 25, 12, 22, 11, 90};42 int n = sizeof(arr) / sizeof(arr[0]);4344 cout << "Original array: ";45 printArray(arr, n);4647 heapSort(arr, n);4849 cout << "Sorted array: ";50 printArray(arr, n);5152 return 0;53}
Sample Output
Sorted array: 11 12 22 25 34 64 90
After all extractions.
In this one
- How an array represents a binary tree
- How heapify restores the heap property
- Why building starts at n / 2 − 1
- Why heap sort is O(n log n) and in place
How it works
- 1
Build a max heap from the last parent down to index 0.
- 2
Swap the root (max) with the last element.
- 3
Shrink the heap by one and heapify the root.
- 4
Repeat until one element remains.
Edge cases
Two elements
Sort 2 1.
Building makes 2 the root, the swap moves it to the end, and heapify on size 1 does nothing: 1 2.
Duplicates
Sort 3 1 3.
Values sort correctly, but equal elements may change relative order; heap sort is not stable.
What's going on
The program sorts an array of integers using the Heap Sort algorithm. For example:
Heap Sort works by treating the array as a binary heap, building a max heap, and then repeatedly extracting the maximum element to build the sorted array from the end.
Header File Used
#include <iostream>
This header provides:
Understanding Heap Sort
Binary Heap Concept:
Algorithm Steps:
Visual Example:
Array: [64, 34, 25, 12, 22, 11, 90]
Build Max Heap:
90
/ \
34 64
/ \ / \
12 22 25 11
Extract Max (90) → place at end
Heapify remaining...
Function: heapify()
void heapify(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);
}
}
How it works:
Heap Property:
Function: heapSort()
void heapSort(int arr[], int n) {
// Build max heap
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// Extract elements from heap
for (int i = n - 1; i > 0; i--) {
swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}
How it works:
Step-by-Step Algorithm
Step 1: Build Max Heap
Step 2: Extract Maximum
Step 3: Restore Heap
Step 4: Repeat
Understanding Binary Heap
Array Representation:
Example (array indices):
Array: [90, 34, 64, 12, 22, 25, 11]
0 1 2 3 4 5 6
Tree:
0(90)
/ \
1(34) 2(64)
/ \ / \
3(12) 4(22) 5(25) 6(11)
Heap Property:
Time and Space Complexity
Time Complexity: O(n log n) in all cases
Space Complexity: O(1)
Stability: Not Stable
When to Use Heap Sort
Best For:
Not Recommended For:
Important Considerations
Building Heap:
Heap Size:
Heapify Direction:
return 0;
This ends the program successfully.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Left child of index 3?
Pick an answer to check it.
Question 2
What is at the root of a max heap?
Pick an answer to check it.
Questions people ask
Children of index i?
Left 2i + 1, right 2i + 2.
Why start at n / 2 − 1?
Indexes after that are leaves, which are already valid heaps.
Extra memory?
O(1) besides the recursion in heapify.