Binary heaps and priority queues
A complete binary tree with the biggest (or smallest) key on top — the engine behind priority queues and heap sort.
Syllabus says: “Binary Heaps - Binary Heap Operations, Priority Queue”
On this page · 13 sections
Heap = complete SHAPE + heap ORDER. Insert → add at the end, BUBBLE UP. Delete → move the last to the root, SINK DOWN.
A college hierarchy: the principal (biggest) on top; every head of department is above their own staff. Nobody cares how two departments compare with each other.
A max-heap is a complete binary tree in which the key of every node is greater than or equal to the keys of its children (min-heap: less than or equal); insertion and deletion of the root take O(log n).
What you will be able to do
- Compare min-heap and max-heap (Nov 2025 Q5).
- Insert and delete the root, showing every swap.
- Build a heap with heapify (May 2026 Q16b).
- Explain priority queues and compare them with deques (model paper Q10b).
Min-heap vs max-heap
| Max-heap | Min-heap | |
|---|---|---|
| Order rule | parent ≥ children | parent ≤ children |
| Root holds | the largest key | the smallest key |
| Shape | complete binary tree | complete binary tree |
| Used for | heap sort (ascending), max-priority queue | Dijkstra, merging k sorted lists, min-priority queue |
Priority queues
A priority queue is an ADT where each element has a priority and the element with the highest (or lowest) priority is removed first. A heap implements insert and deleteMax in O(log n) and findMax in O(1).
- CPU scheduling by priority; hospital emergency triage.
- Dijkstra's shortest path (min-priority queue).
- Merging k sorted lists (model paper Q16a): put the first element of each list into a min-heap; repeatedly extract the minimum and insert the next element from the same list → O(N log k) for N total elements.
Worked example
- i = 2 (30): children 8, 24 — already larger. No change.
- i = 1 (12): larger child 25 → swap → [20, 25, 30, 12, 18, 8, 24].
- i = 0 (20): larger child 30 → swap; 20 now at index 2, larger child 24 → swap → [30, 25, 24, 12, 18, 8, 20].
Delete the root (30): move the last element 20 to the root → [20, 25, 24, 12, 18, 8]. Sift down: larger child 25 → swap → [25, 20, 24, 12, 18, 8]. 20's children 12 and 18 are smaller — stop.
Now watch it run
Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶. Keys: Space play/pause, ← → step.
Also try: Min-heap
Algorithms (0-based array: children 2i + 1, 2i + 2)
Algorithm Insert(heap, n, key) // max-heap
1. i ← n; heap[i] ← key; n ← n + 1
2. while i > 0 and heap[(i−1)/2] < heap[i] do // bubble up
3. swap heap[i], heap[(i−1)/2]; i ← (i−1)/2
Algorithm DeleteMax(heap, n)
1. if n = 0 then print "Heap empty"; return
2. max ← heap[0]; heap[0] ← heap[n−1]; n ← n − 1
3. SiftDown(heap, n, 0)
4. return max
Algorithm SiftDown(heap, n, i)
1. loop
2. big ← i; l ← 2i + 1; r ← 2i + 2
3. if l < n and heap[l] > heap[big] then big ← l
4. if r < n and heap[r] > heap[big] then big ← r
5. if big = i then return
6. swap heap[i], heap[big]; i ← big
Algorithm BuildHeap(heap, n) // heapify
1. for i ← ⌊n/2⌋ − 1 down to 0 do SiftDown(heap, n, i)C implementation
binary_heap.ctested ✓ 199/199 cases/* Binary heap and priority queue (array) — KTU PCCST303, Module 3 (KTU May 2026 Q16b)
* Root at index 0; children of i are 2i+1 and 2i+2; parent is (i-1)/2.
* First token: MAX or MIN. Commands:
* B n k1 .. kn build a heap bottom-up from the keys (O(n))
* I x insert: put x at the end and sift it up
* D delete the root: move the last key to the root and sift it down
* After every command: optional result line, then "HEAP: a[0] a[1] ...". */
#include <stdio.h>
#include <string.h>
#define CAP 100
int a[CAP], n = 0, isMax = 1;
int beats(int x, int y) { return isMax ? x > y : x < y; } /* should x be above y? */
void swap(int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }
void siftUp(int i) {
while (i > 0 && beats(a[i], a[(i - 1) / 2])) { swap(i, (i - 1) / 2); i = (i - 1) / 2; }
}
void siftDown(int i) {
for (;;) {
int l = 2 * i + 1, r = 2 * i + 2, b = i;
if (l < n && beats(a[l], a[b])) b = l;
if (r < n && beats(a[r], a[b])) b = r;
if (b == i) return;
swap(i, b);
i = b;
}
}
void insert(int x) {
if (n == CAP) { printf("OVERFLOW\n"); return; }
a[n] = x;
siftUp(n++);
}
void deleteRoot(void) {
if (n == 0) { printf("UNDERFLOW\n"); return; }
printf("removed %d\n", a[0]);
a[0] = a[--n];
siftDown(0);
}
void build(void) { int i; for (i = n / 2 - 1; i >= 0; i--) siftDown(i); }
int main(void) {
char kind[4], cmd[4];
int i, k, x;
if (scanf("%3s", kind) != 1) return 1;
isMax = strcmp(kind, "MIN") != 0;
while (scanf("%3s", cmd) == 1) {
if (cmd[0] == 'B' && scanf("%d", &k) == 1 && k >= 0 && k <= CAP) {
n = 0;
for (i = 0; i < k && scanf("%d", &x) == 1; i++) a[n++] = x;
build();
} else if (cmd[0] == 'I' && scanf("%d", &x) == 1) insert(x);
else if (cmd[0] == 'D') deleteRoot();
else { printf("BAD COMMAND\n"); break; }
printf("HEAP:");
for (i = 0; i < n; i++) printf(" %d", a[i]);
printf("\n");
}
return 0;
}
Sample run · May 2026 Q16b · real output from gcc
Input (stdin)
MAX B 7 20 12 30 25 18 8 24 D
Output (stdout)
HEAP: 30 25 24 12 18 8 20 removed 30 HEAP: 25 20 24 12 18 8
Complexity
| Operation | Time |
|---|---|
| find max / min | O(1) |
| insert | O(log n) |
| delete root | O(log n) |
| build heap (heapify) | O(n) |
| build by n inserts | O(n log n) |
Asked in KTU exams (4)
- November 2025 · Q53 marksCompare Min-heap and Max-heap with example.
- May 2026 · Q16b3 markssolved ✓Create a Max-heap from 20, 12, 30, 25, 18, 8 and 24 using heapify. Then delete root element from the tree.
- — 2024 · Q10b4 marksCompare priority queues and deques in terms of structure, use cases, and operations.
- — 2024 · Q16a6 marksYou are given k sorted linked lists. Your task is to merge them into one sorted list. Use a min-heap (priority queue) to optimize the merging process. Always insert the smallest available element into the result list by extracting it from the heap and then pushing the next element from the same source list, if it exists.
Quick check — can you get them all?
Practice
Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.
Exam-ready summary
- Complete tree + heap order.
- Insert: put at the end, bubble up. Delete: last → root, sift down.
- Heapify from ⌊n/2⌋ − 1 down to 0: O(n).
- Priority queue = the ADT; heap = the usual implementation.
References
- Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — §5.6 (Heaps)
- Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, 3/e — Ch. 6
Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.
Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)