DATA STRUCTURES PROGRAM • HEAPS, HASHING & DISJOINT SETS
Build a Max-Heap from an Array
Learn how to build a max-heap from an array using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
10 5 3 4 1
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
void heapify(int values[], int size, int root)
{
while (1) {
int largest = root, left = 2 * root + 1, right = left + 1;
if (left < size && values[left] > values[largest]) largest = left;
if (right < size && values[right] > values[largest]) largest = right;
if (largest == root) return;
int temporary = values[root]; values[root] = values[largest]; values[largest] = temporary;
root = largest;
}
}
int main(void)
{
int values[] = {4, 10, 3, 5, 1};
int size = 5;
for (int index = size / 2 - 1; index >= 0; index--) heapify(values, size, index);
for (int index = 0; index < size; index++) printf("%d ", values[index]);
putchar('\n');
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
10 5 3 4 1
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Heapify every internal node from the bottom level toward the root.
- Display the computed result.
Heapify every internal node from the bottom level toward the root.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
Auxiliary space
O(n)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
