Build Heap from Array Heapify in DSA C++ - Time & Space Complexity
We want to understand how long it takes to build a heap from an unsorted array using heapify.
How does the time needed grow as the array gets bigger?
Analyze the time complexity of the following code snippet.
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) {
std::swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
void buildHeap(int arr[], int n) {
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
}
This code builds a max heap from an unsorted array by calling heapify from the bottom non-leaf nodes up to the root.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The heapify function called on each non-leaf node.
- How many times: The for loop calls heapify about n/2 times, once for each non-leaf node.
- Each heapify call may recurse down the tree, but the depth depends on the node's height.
Heapify work depends on node height; nodes near bottom do less work, nodes near top do more.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20-30 operations |
| 100 | About 300-400 operations |
| 1000 | About 4000-5000 operations |
Pattern observation: The total work grows roughly linearly with input size, not quadratically.
Time Complexity: O(n)
This means building a heap from an array takes time proportional to the number of elements.
[X] Wrong: "Heapify is called n/2 times and each call can take up to log n, so total time is O(n log n)."
[OK] Correct: Most heapify calls happen on nodes near the bottom with small height, so they do less work. The total sums up to O(n), not O(n log n).
Knowing that building a heap is O(n) helps you explain efficient data structure setup in interviews confidently.
"What if we used a different method that inserts elements one by one into an empty heap? How would the time complexity change?"
Practice
heapify process when building a heap from an array?Solution
Step 1: Understand heap property
A heap is a special tree where each parent node is greater (max-heap) or smaller (min-heap) than its children.Step 2: Role of heapify
Heapify rearranges elements so this property holds for every subtree starting from a node.Final Answer:
To rearrange elements to satisfy the heap property -> Option CQuick Check:
Heapify = rearrange for heap property [OK]
- Thinking heapify sorts the array
- Confusing heapify with finding max element
- Assuming heapify reverses the array
heapify on an array arr of size n starting from index i in C++?Solution
Step 1: Understand heapify parameters
Heapify usually takes the array, its size, and the index to heapify from in that order.Step 2: Match correct syntax
heapify(arr, n, i); matches the standard signature: heapify(arr, n, i); others have wrong order.Final Answer:
heapify(arr, n, i); -> Option DQuick Check:
heapify(arr, size, index) = B [OK]
- Mixing parameter order
- Passing index before array
- Confusing size and index positions
arr = [4, 10, 3, 5, 1], what will be the array after calling heapify(arr, 5, 0) assuming a max-heap?Solution
Step 1: Identify root and children
Index 0 has value 4; children at indices 1 and 2 are 10 and 3.Step 2: Swap with largest child and heapify
Swap 4 with 10 (largest child). Now at index 1, value 4 has children 5 and 1. Swap 4 with 5. Final array: [10, 5, 3, 4, 1]Final Answer:
[10, 5, 3, 4, 1] -> Option AQuick Check:
Max-heap root fixed = [10, 5, 3, 4, 1] [OK]
- Not swapping with largest child
- Stopping after first swap
- Confusing min-heap with max-heap
arr of size n. Identify the error:
for (int i = 0; i <= n/2; i++) {
heapify(arr, n, i);
}Solution
Step 1: Understand heap building order
Heap building requires heapify from last non-leaf node down to root, i.e., from n/2 - 1 down to 0.Step 2: Identify loop direction and range error
The loop incorrectly goes from 0 up to n/2, which is wrong direction and range.Final Answer:
Loop should start from n/2 - 1 and go down to 0 -> Option BQuick Check:
Build heap loops down from n/2-1 [OK]
- Looping forward instead of backward
- Starting loop at 0 without decrement
- Calling heapify with wrong index
arr = [3, 9, 2, 1, 4, 5]. After building a max heap using the standard heapify method, what is the final array?Solution
Step 1: Start heapify from last non-leaf node
Last non-leaf index = n/2 -1 = 2. Heapify at index 2: children 5 and none, 2 < 5, swap to get [3,9,5,1,4,2].Step 2: Heapify at index 1
Index 1 value 9, children 1 and 4. 9 is largest, no change.Step 3: Heapify at index 0
Index 0 value 3, children 9 and 5. Swap 3 with 9: [9,3,5,1,4,2]. Heapify at index 1: value 3, children 1 and 4. Swap 3 with 4: [9,4,5,1,3,2].Final Answer:
[9, 4, 5, 1, 3, 2] -> Option AQuick Check:
Max heap built = [9,4,5,1,3,2] [OK]
- Not heapifying all parents
- Swapping with wrong child
- Stopping heapify early
Ready to prove it?
Pass the test and this pattern moves unknown
