In a hospital emergency room, patients are not seen in the order they arrive. The most urgent case goes first. A priority queue works the same way: you can add items in any order, and you always remove the most important one next. The usual way to build one is a binary heap, a tree stored inside an ordinary array. It adds and removes items in O(log n) time. This lesson builds a min-heap, a task priority queue, and heap sort.
In this lesson you will learn
- The heap property and how a tree fits in an array
- Finding parents and children with index arithmetic
- Insert with “sift up” and remove with “sift down”
- A priority queue of tasks with tie-breaking
- Heap sort
You should know arrays, structures and binary search trees.
A Tree Inside an Array
In a min-heap, every parent is smaller than or equal to its children, so the smallest item is always at the top. The tree is complete: every level is full except perhaps the last, which fills from the left. That shape lets us store it in an array with no pointers at all:
- The root is at index 0.
- The children of index i are at 2i + 1 and 2i + 2.
- The parent of index i is at (i − 1) / 2, using integer division.
Building a Min-Heap
#include <stdio.h>
#include <stdbool.h>
#define MAXN 32
/* A min-heap stored in an array.
For the item at index i: parent = (i-1)/2, children = 2i+1 and 2i+2. */
typedef struct { int a[MAXN]; int n; } Heap;
static void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }
static bool heap_push(Heap *h, int v) {
if (h->n == MAXN) return false;
int i = h->n++;
h->a[i] = v;
while (i > 0 && h->a[(i - 1) / 2] > h->a[i]) { /* sift up */
swap(&h->a[(i - 1) / 2], &h->a[i]);
i = (i - 1) / 2;
}
return true;
}
static bool heap_pop(Heap *h, int *out) {
if (h->n == 0) return false;
*out = h->a[0];
h->a[0] = h->a[--h->n]; /* last item to the top */
int i = 0;
for (;;) { /* sift down */
int l = 2 * i + 1, r = l + 1, small = i;
if (l < h->n && h->a[l] < h->a[small]) small = l;
if (r < h->n && h->a[r] < h->a[small]) small = r;
if (small == i) break;
swap(&h->a[i], &h->a[small]);
i = small;
}
return true;
}
static void show(const Heap *h) {
printf("array: ");
for (int i = 0; i < h->n; i++) printf("%d ", h->a[i]);
printf("\n");
}
int main(void) {
Heap h = {.n = 0};
int values[] = {42, 17, 8, 23, 5, 31, 12};
for (int i = 0; i < 7; i++) heap_push(&h, values[i]);
show(&h);
printf("smallest is always at a[0]: %d\n", h.a[0]);
int v;
printf("popping: ");
while (heap_pop(&h, &v)) printf("%d ", v);
printf("\n");
return 0;
}
Output
array: 5 8 12 42 23 31 17
smallest is always at a[0]: 5
popping: 5 8 12 17 23 31 42
heap_pushputs the new value at the end of the array, then sifts it up: while it is smaller than its parent, the two swap places. It climbs at most the height of the tree, about log₂ n steps.- After inserting 42, 17, 8, 23, 5, 31 and 12, the array is 5 8 12 42 23 31 17. It is not sorted, but every parent is smaller than its children, and 5 is at the top.
heap_poptakes the top item, moves the last item into its place, then sifts it down: it swaps with its smaller child until neither child is smaller.- Popping until empty returns the values in increasing order.
A Task Priority Queue and Heap Sort
#include <stdio.h>
#include <string.h>
/* Priority queue of tasks: highest priority first (a max-heap on priority).
Ties are broken by arrival order, so equal priorities stay first come, first served. */
typedef struct { char name[24]; int priority; int seq; } Task;
typedef struct { Task a[16]; int n; int next_seq; } PQ;
static int before(const Task *x, const Task *y) { /* should x come out before y? */
if (x->priority != y->priority) return x->priority > y->priority;
return x->seq < y->seq;
}
static void swap(Task *x, Task *y) { Task t = *x; *x = *y; *y = t; }
static void pq_push(PQ *q, const char *name, int priority) {
int i = q->n++;
snprintf(q->a[i].name, sizeof q->a[i].name, "%s", name);
q->a[i].priority = priority;
q->a[i].seq = q->next_seq++;
while (i > 0 && before(&q->a[i], &q->a[(i - 1) / 2])) {
swap(&q->a[i], &q->a[(i - 1) / 2]);
i = (i - 1) / 2;
}
}
static Task pq_pop(PQ *q) {
Task top = q->a[0];
q->a[0] = q->a[--q->n];
int i = 0;
for (;;) {
int l = 2 * i + 1, r = l + 1, best = i;
if (l < q->n && before(&q->a[l], &q->a[best])) best = l;
if (r < q->n && before(&q->a[r], &q->a[best])) best = r;
if (best == i) break;
swap(&q->a[i], &q->a[best]);
i = best;
}
return top;
}
/* Heap sort: build a max-heap in place, then move the max to the end repeatedly */
static void sift_down(int *a, int n, int i) {
for (;;) {
int l = 2 * i + 1, r = l + 1, big = i;
if (l < n && a[l] > a[big]) big = l;
if (r < n && a[r] > a[big]) big = r;
if (big == i) return;
int t = a[i]; a[i] = a[big]; a[big] = t;
i = big;
}
}
static void heap_sort(int *a, int n) {
for (int i = n / 2 - 1; i >= 0; i--) sift_down(a, n, i);
for (int end = n - 1; end > 0; end--) {
int t = a[0]; a[0] = a[end]; a[end] = t;
sift_down(a, end, 0);
}
}
int main(void) {
PQ q = {.n = 0, .next_seq = 0};
pq_push(&q, "reply to email", 2);
pq_push(&q, "server is down", 9);
pq_push(&q, "update report", 2);
pq_push(&q, "fix login bug", 7);
pq_push(&q, "order snacks", 1);
pq_push(&q, "security patch", 9);
printf("tasks by priority:\n");
while (q.n > 0) {
Task t = pq_pop(&q);
printf(" [%d] %s\n", t.priority, t.name);
}
int marks[] = {64, 25, 12, 22, 11, 90, 47};
heap_sort(marks, 7);
printf("heap sort: ");
for (int i = 0; i < 7; i++) printf("%d ", marks[i]);
printf("\n");
return 0;
}
Output
tasks by priority:
[9] server is down
[9] security patch
[7] fix login bug
[2] reply to email
[2] update report
[1] order snacks
heap sort: 11 12 22 25 47 64 90
- This queue is a max-heap on priority: higher numbers come out first. The only change from the min-heap is the comparison function,
before. - Heaps are not stable on their own: equal items can come out in any order. Each task gets a sequence number when it is added, and
beforeuses it to break ties. So “server is down” (added first) comes before “security patch”, and “reply to email” before “update report”. - Heap sort first turns the array into a max-heap in place, starting from the last parent,
n / 2 - 1. Then it swaps the largest item to the end, shrinks the heap by one and sifts down. It repeats until the heap is empty. - Heap sort runs in O(n log n) time, even in the worst case, and needs no extra memory.
| Operation | Binary heap | Sorted array | Unsorted array |
|---|---|---|---|
| Insert | O(log n) | O(n) | O(1) |
| Look at top | O(1) | O(1) | O(n) |
| Remove top | O(log n) | O(1) or O(n) | O(n) |
Priority queues power task schedulers, event simulations, “top K” problems, and graph algorithms such as Dijkstra’s shortest path.
Common Mistakes
- Wrong index formulas, such as children at
2iand2i + 1. Those are for arrays that start at index 1. - Sifting down by comparing with only one child. Always swap with the smaller (or, for a max-heap, larger) of the two.
- Forgetting the bounds check on children: a child index can be past
n. - Expecting the heap array to be sorted. Only the top is guaranteed.
Practice Exercises
Exercise 1. In a heap array, what are the parent of index 9 and the children of index 4?
Show answer
Parent of 9: (9 − 1) / 2 = 4. Children of 4: 2 × 4 + 1 = 9 and 2 × 4 + 2 = 10.
Exercise 2. Is the array {3, 5, 4, 9, 6, 2} a valid min-heap? If not, which item breaks the rule?
Show answer
No. The item 2 at index 5 has parent index 2, which holds 4. A child (2) is smaller than its parent (4), so the heap property fails.
Frequently Asked Questions
Is a heap the same as heap memory from malloc?
No. They share a name but nothing else. The “heap” where malloc gets memory is a region managed by the system; the binary heap is a data structure.
How do I find the K largest numbers in a huge list?
Keep a min-heap of size K. For each number, if it is bigger than the heap’s top, replace the top and sift down. At the end the heap holds the K largest, and it took O(n log K) time with only K items in memory.
Summary
- A binary heap is a complete tree stored in an array; the top is the smallest (or largest) item.
- Children of i are 2i + 1 and 2i + 2; the parent is (i − 1) / 2.
- Push sifts up, pop sifts down; both take O(log n).
- A heap gives you a priority queue and heap sort.
Next: C Project: Inventory Manager.
