Skip to content
Azhimathi Mayam logoDSA Study HubPCCST303 · KTU · S3
Module 3 · syllabusAsked 4× in KTU papersLesson live

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
ormakkurippu ✎
Never-forget card

Heap = complete SHAPE + heap ORDER. Insert → add at the end, BUBBLE UP. Delete → move the last to the root, SINK DOWN.

Picture it

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.

Write this in the exam

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-heapMin-heap
Order ruleparent ≥ childrenparent ≤ children
Root holdsthe largest keythe smallest key
Shapecomplete binary treecomplete binary tree
Used forheap sort (ascending), max-priority queueDijkstra, merging k sorted lists, min-priority queue
1225183082420
Max-heap [30, 25, 24, 12, 18, 8, 20] — stored in an array level by level.

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

2512182083024
Input 20, 12, 30, 25, 18, 8, 24 as a complete tree.
  1. i = 2 (30): children 8, 24 — already larger. No change.
  2. i = 1 (12): larger child 25 → swap → [20, 25, 30, 12, 18, 8, 24].
  3. i = 0 (20): larger child 30 → swap; 20 now at index 2, larger child 24 → swap → [30, 25, 24, 12, 18, 8, 20].
1225183082420
Max-heap.

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.

12201825824
After deleting the root: [25, 20, 24, 12, 18, 8].

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 ◀ ▶.

Loading visualizer…

Also try: Min-heap

Algorithms (0-based array: children 2i + 1, 2i + 2)

algorithm
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
C
/* 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

Open in the Code Lab →

Complexity

OperationTime
find max / minO(1)
insertO(log n)
delete rootO(log n)
build heap (heapify)O(n)
build by n insertsO(n log n)

Asked in KTU exams (4)

Quick check — can you get them all?

Question 1

Q1.Max-heap from 20, 12, 30, 25, 18, 8, 24 using heapify (array)?

Question 2

Q2.Deleting the root of a heap with n elements costs…

Question 3

Q3.Building a heap bottom-up (heapify) from n elements costs…

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)