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.

IntermediateMin-heapInsertionHeapify up

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
5 10 40 30 20

COMPLETE C PROGRAM

Complete C implementation

dsa-min-heap-insertion.c
Open in compiler
#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;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

5 10 40 30 20
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Append each value and swap it upward until its parent is no larger.
  3. 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.