DATA STRUCTURES PROGRAM • HEAPS, HASHING & DISJOINT SETS
Insert Values into a Min-Heap
Learn how to insert values into a min-heap using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
5 10 40 30 20
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int heap[20], size = 0;
int values[] = {30, 10, 40, 5, 20};
for (int index = 0; index < 5; index++) {
int position = size++;
heap[position] = values[index];
while (position > 0) {
int parent = (position - 1) / 2;
if (heap[parent] <= heap[position]) break;
int temporary = heap[parent]; heap[parent] = heap[position]; heap[position] = temporary;
position = parent;
}
}
for (int index = 0; index < size; index++) printf("%d ", heap[index]);
putchar('\n');
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
5 10 40 30 20
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Append each value and swap it upward until its parent is no larger.
- Display the computed result.
Append each value and swap it upward until its parent is no larger.
EFFICIENCY
Time and space complexity
Time complexity
O(log n) per insertion
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.
