DATA STRUCTURES PROGRAM • HEAPS, HASHING & DISJOINT SETS

Delete the Root from a Min-Heap

Learn how to delete the root from a min-heap using a clear C program.

IntermediateMin-heapExtract minimumHeapify down

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Removed = 5
Heap: 10 30 20 40

COMPLETE C PROGRAM

Complete C implementation

dsa-min-heap-delete-root.c
Open in compiler
#include <stdio.h>

int main(void)
{
    int heap[] = {5, 10, 20, 30, 40};
    int size = 5, minimum = heap[0];
    heap[0] = heap[--size];
    int position = 0;
    while (1) {
        int left = 2 * position + 1, right = left + 1, smallest = position;
        if (left < size && heap[left] < heap[smallest]) smallest = left;
        if (right < size && heap[right] < heap[smallest]) smallest = right;
        if (smallest == position) break;
        int temporary = heap[position]; heap[position] = heap[smallest]; heap[smallest] = temporary;
        position = smallest;
    }
    printf("Removed = %d\nHeap: ", minimum);
    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

Removed = 5
Heap: 10 30 20 40
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Move the final value to the root and swap it down with its smaller child.
  3. Display the computed result.

Move the final value to the root and swap it down with its smaller child.

EFFICIENCY

Time and space complexity

Time complexity

O(log 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.