Heap sort first builds a max heap from the array in O(n). It then repeatedly swaps the root (maximum) with the last element, shrinks the heap by one, and heapifies the root. After n - 1 rounds the array is sorted ascending. It is O(n log n) in every case, in place, and not stable.
Remember
build max heap
for (i = n - 1; i > 0; i--) {
swap(a[0], a[i]);
heapify(a, i, 0); /* heap size is now i */
}
Reference
Cheat Sheet
Keep these facts handy while you work with Heap Sort in C.
Topic
Detail
Time
O(n log n) always
Space
O(1)
Stable
No
Needs
Heapify routine
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Shell Sort.
Example 1 — Build the heap, then sort
Sort 12, 11, 13, 5, 6, 7.
C
#include <stdio.h>
static void heapify(int a[], int n, int i) {
for (;;) {
int l = 2 * i + 1, r = l + 1, s = i;
if (l < n && a[l] > a[s]) s = l;
if (r < n && a[r] > a[s]) s = r;
if (s == i) return;
int t = a[i]; a[i] = a[s]; a[s] = t;
i = s;
}
}
static void show(const char *label, const int a[], int n) {
printf("%s", label);
for (int i = 0; i < n; i++) printf(" %d", a[i]);
printf("\n");
}
int main(void) {
int a[] = {12, 11, 13, 5, 6, 7};
int n = 6;
for (int i = n / 2 - 1; i >= 0; i--) heapify(a, n, i);
show("heap:", a, n);
for (int i = n - 1; i > 0; i--) {
int t = a[0]; a[0] = a[i]; a[i] = t;
heapify(a, i, 0);
}
show("sorted:", a, n);
return 0;
}
Output
heap: 13 11 12 5 6 7
sorted: 5 6 7 11 12 13
How It Works
Building the heap swaps 12 with its larger child 13, giving 13 at the root.
Each round moves the current maximum to the end of the array.
The shrinking heap region and growing sorted tail share the same array.
Edge Cases & Pitfalls
Check these before relying on Heap Sort in real programs.
size
Heapifying the whole array
After each swap, heapify only the first i elements.
cache
Cache behavior
Heap sort jumps around memory and is often slower than quick sort in practice.
Remember
Key Takeaways
Build heap, then extract.
O(n log n), in place.
Not stable.
One line: Heap sort first builds a max heap from the array in O(n).
Frequently Asked Questions
O(n log n) in all cases.
It guarantees O(n log n) with O(1) extra space, which neither merge sort nor quick sort provide together.
Continue with "C Shell Sort" next. Sort elements far apart first, then shrink the gap to 1. The C Sorting Algorithms hub lists every topic in order.