Min-heap in C: solved exercise
Min-heap in C: solved exercise
If you searched for a solved min-heap in C, here is the complete array-based implementation: O(log n) insertion, O(log n) extract-min, and the heapify operation that maintains the heap property.
A min-heap is a complete binary tree where each node is less than or equal to its children. It is efficiently represented with an array: the left child of node i is at 2*i+1, the right at 2*i+2, and the parent at (i-1)/2.
Problem statement
Implement a fixed-capacity min-heap supporting:
insert(heap, value): inserts an element and restores the heap property.extract_min(heap): removes and returns the minimum element.print(heap): displays the internal array.
Insert the values {5, 3, 8, 1, 4, 2} and extract the minimum three times.
C solution
Expected output
Common mistakes
- Wrong child/parent index formulas: left child =
2*i+1, right child =2*i+2, parent =(i-1)/2. With 1-based indexing the formulas differ. - Not decrementing
sizebefore callingpush_downinextract_min: ifsizeis not reduced, the last element placed at the root is compared with itself. - Confusing min-heap and max-heap: in a min-heap the parent is smaller; in a max-heap it is larger. Only the comparison sign changes.
- Not validating that the heap is non-empty before
extract_min: accessingdata[0]whensize == 0is undefined behavior.
Practical use
The min-heap is the underlying structure of priority queues, used in Dijkstra’s algorithm, Huffman encoding, task scheduling by priority, and the heapsort sorting algorithm.
Recommended next exercise
- Heap sort in C: solved exercise
- Queue in C: solved exercise
- Dijkstra in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Why use an array instead of a pointer-based tree for a heap?
Because a complete binary tree maps perfectly to an array without pointers: parent and child indices are computed arithmetically. This reduces memory usage, improves cache locality, and simplifies the code.
What is the heapify (or build-heap) operation?
It converts an arbitrary array into a valid heap in O(n) by applying push_down to all internal nodes from bottom to top (from n/2 - 1 down to 0). This is more efficient than inserting n elements one by one, which costs O(n log n).
How do you convert a min-heap into a max-heap?
Only the comparisons need to be inverted: in bubble_up, change <= to >=; in push_down, change < to >. The rest of the code stays identical.