data-structures · advanced · ~15 min
Implement complete binary min-heap priority queue insertion and sift-down extraction.
A binary min-heap arranges items such that the root is always the minimum value. Heap insertion and extraction maintain the heap property in logarithmic time O(log N).
Given the min-heap structure:
typedef struct {
int *data;
size_t size;
size_t capacity;
} MinHeap;
Implement:
int heap_push(MinHeap *h, int val);
int heap_pop_min(MinHeap *h, int *out);
heap_push:h == NULL or h->size >= h->capacity, return -1.val at index h->size, then sift up: compare with parent at (idx - 1) / 2. While idx > 0 and value is smaller than parent, swap with parent and update idx.h->size and return 0.heap_pop_min:h == NULL or out == NULL or h->size == 0, return -1.h->data[0] into *out.h->data[h->size - 1] to h->data[0].h->size.2 * idx + 1 and 2 * idx + 2. If root element is greater than smaller child, swap with smaller child and continue; otherwise break.0.int store[10]; MinHeap h = { store, 0, 10 };
heap_push(&h, 30); heap_push(&h, 10); heap_push(&h, 20);
int m;
heap_pop_min(&h, &m); // m == 10
heap_pop_min(&h, &m); // m == 20
h: pointer to MinHeap; val: int; out: pointer to int destination.
Returns 0 on success, -1 on empty/full or NULL.
In-place array sift-up and sift-down. O(log N) operations.
#include <stddef.h>
typedef struct {
int *data;
size_t size;
size_t capacity;
} MinHeap;
int heap_push(MinHeap *h, int val) {
(void)h; (void)val;
return -1;
}
int heap_pop_min(MinHeap *h, int *out) {
(void)h; (void)out;
return -1;
}
Off-by-one in child index computation; forgetting to check right child existence before comparing.
Extracting from heap of size 1; pushing duplicate values; empty heap pop returns -1.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.