Reading history

Heap Data Structure in C: Priority Queue and Heap Sort

5 min read 0 views

Learn heaps in C: the heap property, array layout, sift up and sift down, a min-heap priority queue, heap sort and common uses.

A heap is a complete binary tree with one ordering rule. In a min-heap every parent is smaller than or equal to its children, so the smallest value is always at the root; a max-heap is the reverse. Heaps give you the minimum (or maximum) instantly and let you add or remove items in O(log n) time. They are how priority queues are built, and they power heap sort and Dijkstra’s shortest-path algorithm.

In this lesson you will learn

  • The heap property and why heaps are stored in arrays
  • Insert with “sift up” and remove with “sift down”
  • Building a min-heap priority queue in C
  • Heap sort
  • Where heaps are used

A Tree Stored in an Array

Because a heap is a complete tree, filled level by level from the left, it fits in an array with no gaps and no pointers. For the element at index i:

RelativeIndex
Parent(i - 1) / 2
Left child2 * i + 1
Right child2 * i + 2

A Min-Heap Priority Queue

#include <stdio.h>

#define CAP 32
int heap[CAP];
int size = 0;

void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }

/* Min-heap: parent of i is (i-1)/2, children are 2i+1 and 2i+2 */
void push(int x) {
    int i = size++;
    heap[i] = x;
    while (i > 0 && heap[(i - 1) / 2] > heap[i]) {      /* sift up */
        swap(&heap[(i - 1) / 2], &heap[i]);
        i = (i - 1) / 2;
    }
}

int pop(void) {
    int top = heap[0];
    heap[0] = heap[--size];
    int i = 0;
    for (;;) {                                           /* sift down */
        int l = 2 * i + 1, r = 2 * i + 2, smallest = i;
        if (l < size && heap[l] < heap[smallest]) smallest = l;
        if (r < size && heap[r] < heap[smallest]) smallest = r;
        if (smallest == i) break;
        swap(&heap[i], &heap[smallest]);
        i = smallest;
    }
    return top;
}

int main(void) {
    int values[] = {42, 7, 19, 3, 25, 11, 3};
    for (int i = 0; i < 7; i++) push(values[i]);

    printf("Heap array: ");
    for (int i = 0; i < size; i++) printf("%d ", heap[i]);
    printf("\nMinimum (peek): %d\n", heap[0]);

    printf("Popping in order: ");
    while (size > 0) printf("%d ", pop());
    printf("\n");
    return 0;
}

Output

Heap array: 3 7 3 42 25 19 11 
Minimum (peek): 3
Popping in order: 3 3 7 11 19 25 42
  • Push puts the new value at the end of the array, then sifts it up, swapping with its parent while the parent is larger. The path is at most the tree’s height, so this is O(log n).
  • Pop takes the root (the minimum), moves the last element to the root and sifts it down, swapping with the smaller child until the heap rule holds again. Also O(log n).
  • Peek is just heap[0]: O(1).
  • The heap array 3 7 3 42 25 19 11 is not sorted; only the parent-child rule holds. Popping repeatedly, however, returns the values in sorted order, duplicates included.

Heap Sort

#include <stdio.h>

void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }

/* Sift a[i] down within a[0..n-1] for a MAX-heap */
void heapify(int a[], int n, int i) {
    for (;;) {
        int l = 2 * i + 1, r = 2 * i + 2, largest = i;
        if (l < n && a[l] > a[largest]) largest = l;
        if (r < n && a[r] > a[largest]) largest = r;
        if (largest == i) return;
        swap(&a[i], &a[largest]);
        i = largest;
    }
}

void heap_sort(int a[], int n) {
    for (int i = n / 2 - 1; i >= 0; i--) heapify(a, n, i);   /* build heap */
    for (int end = n - 1; end > 0; end--) {
        swap(&a[0], &a[end]);          /* move the max to the end */
        heapify(a, end, 0);            /* restore heap on the rest */
    }
}

int main(void) {
    int a[] = {12, 11, 13, 5, 6, 7};
    int n = 6;
    heap_sort(a, n);
    for (int i = 0; i < n; i++) printf("%d ", a[i]);
    printf("\n");
    return 0;
}

Output

5 6 7 11 12 13
  1. Build a max-heap in place by sifting down every non-leaf node, starting from the last one at n/2 - 1. This step takes only O(n) in total.
  2. Repeatedly swap the maximum at the root with the last element of the heap, shrink the heap by one, and sift the new root down.

Heap sort runs in O(n log n) in every case and uses O(1) extra memory, combining the strengths of merge sort (guaranteed time) and quick sort (in place). It is not stable and is usually a little slower than quick sort in practice.

Complexity and Uses

OperationTime
Peek min / maxO(1)
Insert, remove min / maxO(log n)
Build heap from n itemsO(n)
Heap sortO(n log n)
  • Task schedulers and event simulations: always process the most urgent item next.
  • Dijkstra’s algorithm and Prim’s algorithm: pick the closest vertex quickly.
  • Top-k problems: keep a min-heap of size k to find the k largest values in a huge stream.
  • Merging k sorted lists efficiently.

Common Mistakes

  1. Thinking a heap is sorted. Only the root is guaranteed to be the minimum or maximum.
  2. Wrong index formulas when switching between 0-based and 1-based arrays.
  3. Comparing with only one child when sifting down; you must pick the smaller (or larger) child.
  4. Popping from an empty heap or pushing past the array’s capacity.

Practice Exercises

Exercise 1. In a heap array, what are the children of index 3 and the parent of index 6?

Show answer

Children of 3: indexes 7 and 8. Parent of 6: (6 − 1) / 2 = 2 (integer division).

Exercise 2. How would you find the 3 largest numbers in a stream of a million values using little memory?

Show answer

Keep a min-heap of size 3. For each value, if the heap has fewer than 3 items, push it; otherwise, if the value is larger than the heap’s minimum, pop the minimum and push the value. At the end the heap holds the 3 largest. The time is O(n log k) with O(k) memory.

Frequently Asked Questions

Is a heap the same as heap memory?

No. The heap data structure is unrelated to the “heap” area of memory that malloc allocates from. They just share a name.

How do I make a max-heap from the min-heap code?

Reverse every comparison (use < where the min-heap uses >), or store negated values in the min-heap.

Summary

  • A heap is a complete binary tree stored in an array, with parents ≤ children (min-heap).
  • Insert sifts up; remove sifts down; both are O(log n).
  • Heaps implement priority queues; heap sort is O(n log n) and in place.

Next: Graphs, BFS and DFS in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *