data-structures · advanced · ~40 min
Build a max-heap, then repeatedly extract the root into the back of the array.
Sort an array in place using heap sort with a binary max-heap.
Implement void heap_sort(int *a, size_t n) that sorts the n elements of a into non-decreasing order, using an in-place binary max-heap (no extra array).
a: writable array of n ints.n: the number of elements.Nothing returned; a[0..n-1] is sorted in place.
{5,3,8,1,9,2,4,7,6,0} -> {0,1,2,3,4,5,6,7,8,9}
{-3,-1,-5,-2,0,4} -> {-5,-3,-2,-1,0,4}
n == 0 and n == 1 return immediately.malloc. Build a max-heap, then repeatedly swap the root to the back and sift down.Heap sort sorts in place with O(n log n) guaranteed and no recursion. Heaps also underpin priority queues, event schedulers, and OS process scheduling.
a: writable array of n ints; n: element count.
Nothing returned; a is sorted non-decreasing in place.
O(1) auxiliary memory. No malloc.
#include <stddef.h>
void heap_sort(int *a, size_t n) { /* TODO */ }
Off-by-one on parent/child index math; using i/2 when 0-indexed needs (i-1)/2; sifting up instead of down.
n==0, n==1, all-equal arrays, already-heap arrays.
O(n) build-heap, O(n log n) sort. O(1) memory.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.