Heap
A binary heap is a complete binary tree stored in an array, where each parent is ordered with respect to its children. The minimum (or maximum) lives at index zero and can be removed in O(log n).
Detailed Explanation
This is not the malloc heap. It is a priority queue. A min-heap keeps the smallest key at the root. Pushing a value appends it at the end and sifts it up until the parent is smaller. Popping the minimum replaces the root with the last element and sifts that down. Both walks are O(log n) because the tree is kept complete: every level is full except the last, which is filled left to right.
Array indexing is the whole trick. For a node at i (zero-based), the parent is (i - 1) / 2, the left child is 2*i + 1, the right child is 2*i + 2. No pointers. len is the number of live elements. cap is the allocated length. Growth is realloc, same as any dynamic array.
Building a heap from n unordered items by pushing one at a time is O(n log n). Floyd's method — sift down from the last parent to the root — is O(n) and is what qsort's cousins and heap-sort use for the initial stage.
C's standard library does not ship a heap. POSIX does not either. You write heap_push / heap_pop, or you use a library. The compare function decides min versus max. Store indices or ids if you need to change a key later; decreasing a key in a min-heap needs a sift-up of that index, which you cannot do if you only have the value.
Heaps do not give you sorted iteration for free. Repeated pop is O(n log n) and empties the heap. If you need the current minimum and also random access to other keys, you want a tree or a heap plus a hash table of indices.
Code Examples
#include <stdio.h>
#include <stdlib.h>
struct Heap {
int *data;
size_t len;
size_t cap;
};
static void swap(int *a, int *b)
{
int t = *a;
*a = *b;
*b = t;
}
static int heap_push(struct Heap *h, int value)
{
if (h->len == h->cap) {
size_t cap = (h->cap == 0) ? 8 : h->cap * 2;
int *p = realloc(h->data, cap * sizeof *p);
if (p == NULL) {
return -1;
}
h->data = p;
h->cap = cap;
}
size_t i = h->len++;
h->data[i] = value;
while (i > 0) {
size_t parent = (i - 1) / 2;
if (h->data[parent] <= h->data[i]) {
break;
}
swap(&h->data[parent], &h->data[i]);
i = parent;
}
return 0;
}
int main(void)
{
struct Heap h = { NULL, 0, 0 };
heap_push(&h, 5);
heap_push(&h, 1);
heap_push(&h, 3);
printf("%d\n", h.data[0]); /* prints: 1 */
free(h.data);
return 0;
}Common Gotchas
This "heap" is unrelated to `malloc`
saying "allocate on the heap" in a function that also uses a binary heap will confuse every reader. Name the struct `PrioQueue` if that helps.
`data[0]` is the min only if you maintained the property after every push and pop
a raw write into the array breaks it.
Pop without a `len == 0` check reads `data[0]` of an empty heap
that is undefined if `data` is `NULL` or a stale slot.