08-heaps
Min-Heap Pop (Sift Down)
Remove the minimum value, move the last item to the root, and sift downward.
Algorithm
Steps
- Store the heap in an array.
- Compare parent and child indexes instead of building explicit tree nodes.
- Swap only when the heap order is violated.
- Print the deterministic final heap state for replay comparison.
Complexity
- Time: O(log n)
- Space: O(1) extra
sift down
After removing the root, the last value moves to the root and swaps with the smaller child until order is restored.
Visual walkthrough
C DSA Implementation
basic.c
#include <stdio.h>
void print_list(int* values, int n) {
printf("[");
for (int i = 0; i < n; i++) { if (i) printf(", "); printf("%d", values[i]); }
printf("]");
}
void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; }
void heap_insert(int* heap, int* n, int value) {
heap[*n] = value; int child = *n; *n = *n + 1;
while (child > 0) {
int parent = (child - 1) / 2;
if (heap[parent] <= heap[child]) break;
swap(&heap[parent], &heap[child]);
child = parent;
}
}
int heap_pop(int* heap, int* n) {
int smallest = heap[0]; heap[0] = heap[*n - 1]; *n = *n - 1;
int parent = 0;
while (1) {
int left = parent * 2 + 1, right = left + 1;
if (left >= *n) break;
int child = left;
if (right < *n && heap[right] < heap[left]) child = right;
if (heap[parent] <= heap[child]) break;
swap(&heap[parent], &heap[child]);
parent = child;
}
return smallest;
}
int main(void) { int heap[16] = {1, 4, 2, 9, 6, 7}; int n = 6; int popped = heap_pop(heap, &n); printf("%d -> ", popped); print_list(heap, n); printf("\n"); }
Output
1 -> [2, 4, 7, 9, 6]
Implementation notes
- C stores the heap in stack array
int heap[16] = {1, 4, 2, 9, 6, 7}with scalar sizeint n = 6;heap_pop(heap, &n)mutates both the array and the caller's size. heap_pop(int* heap, int* n)copiesheap[0]into localsmallest, replaces the root withheap[*n - 1], then shrinks the active heap with*n = *n - 1.- Sift-down uses signed
intindexes:left = parent * 2 + 1andright = left + 1. The loop stops whenleft >= *nor when the parent is already<=the selected child. - The right child is chosen only when
right < *n && heap[right] < heap[left]; swaps callswap(&heap[parent], &heap[child]), which exchanges two slots through pointers using stack temporaryint t. - The trace records
[1, 4, 2, 9, 6, 7], removes1and moves7to root for[7, 4, 2, 9, 6], then swaps with smaller child2to[2, 4, 7, 9, 6]. printf("%d -> ", popped)prints the returned minimum beforeprint_list(int* values, int n)formats the active heap through pointer-decayed array access and comma-separatedprintfcalls.