Heap sort
Build a max-heap, then repeatedly move the root (maximum) to the end.
Syllabus says: “Heap Sort”
On this page · 16 sections
BUILD a max-heap (O(n)), then n − 1 times: SWAP root with the last, SHRINK the heap, SIFT DOWN.
A tournament: the winner (max) is crowned and leaves; the remaining players replay just a few matches to find the next winner.
Heap sort builds a max-heap from the array and repeatedly swaps the root (maximum) with the last element of the heap, reduces the heap size by one and restores the heap property.
Learning objectives
- View an array as a complete binary tree.
- Build a max-heap bottom-up with heapify.
- Perform the extraction phase and state its O(n log n) cost.
Prerequisites
Complete binary trees and binary heaps (Module 3).
Definition
With 0-based indexing, the children of a[i] are a[2i+1] and a[2i+2] and its parent is a[⌊(i−1)/2⌋]. A max-heap satisfies a[parent] ≥ a[child] everywhere. Heap sort builds a max-heap, then for end = n−1 down to 1 swaps a[0] with a[end] and restores the heap on a[0..end−1].
Two phases
- Build heap: call Heapify(i) for i = ⌊n/2⌋ − 1 down to 0. Heapify sifts a[i] down, swapping with the larger child until it is ≥ both children.
- Sort: swap the root with the last heap element (the maximum is now final), shrink the heap by one, and Heapify(0).
Some textbooks use 1-based arrays (children 2i and 2i+1). The resulting heap is identical; only the index arithmetic changes. State which one you use.
Worked example
| Input | 4 10 3 5 1 |
|---|---|
| Max-heap built | 10 5 3 4 1 |
| After extraction 1 | 5 4 3 1 10 |
| After extraction 2 | 4 1 3 5 10 |
| After extraction 3 | 3 1 4 5 10 |
| After extraction 4 | 1 3 4 5 10 |
Totals: comparisons = 12, swaps = 9
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 ◀ ▶. Keys: Space play/pause, ← → step.
Algorithm / pseudocode
- 1HeapSort(a, n)
- 2for i ← ⌊n/2⌋ − 1 down to 0: Heapify(a, i, n)
- 3for end ← n − 1 down to 1
- 4swap a[0], a[end] // max goes to its final place
- 5Heapify(a, 0, end)
- 6Heapify: largest ← max of a[i], a[2i+1], a[2i+2] (within size)
- 7if largest ≠ i: swap a[i], a[largest]; continue at largest
- 8else stop
- 9end
C implementation
heap_sort.ctested ✓ 132/132 cases/* Heap sort using a max-heap — KTU PCCST303, Module 4
* 0-based array: children of i are 2i+1 and 2i+2.
* Input : n followed by n integers
* Output: the heap after building, the array after every extraction,
* then the sorted array. */
#include <stdio.h>
#define MAX 100
void printArray(const char *label, int a[], int n) {
printf("%s:", label);
for (int i = 0; i < n; i++) printf(" %d", a[i]);
printf("\n");
}
void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }
/* sift a[i] down within a[0..size-1] */
void heapify(int a[], int i, int size) {
while (1) {
int largest = i, l = 2 * i + 1, r = 2 * i + 2;
if (l < size && a[l] > a[largest]) largest = l;
if (r < size && a[r] > a[largest]) largest = r;
if (largest == i) break;
swap(&a[i], &a[largest]);
i = largest;
}
}
void heapSort(int a[], int n) {
for (int i = n / 2 - 1; i >= 0; i--) /* build max-heap bottom-up */
heapify(a, i, n);
printArray("PASS", a, n);
for (int end = n - 1; end >= 1; end--) {
swap(&a[0], &a[end]); /* max to its final place */
heapify(a, 0, end);
printArray("PASS", a, n);
}
}
int main(void) {
int n, a[MAX];
if (scanf("%d", &n) != 1 || n < 0 || n > MAX) { printf("Invalid n\n"); return 1; }
for (int i = 0; i < n; i++)
if (scanf("%d", &a[i]) != 1) { printf("Invalid input\n"); return 1; }
heapSort(a, n);
printArray("SORTED", a, n);
return 0;
}
Sample run · KTU PYQ input · real output from gcc
Input (stdin)
7 20 12 30 25 18 8 24
Output (stdout)
PASS: 30 25 24 12 18 8 20 PASS: 25 20 24 12 18 8 30 PASS: 24 20 8 12 18 25 30 PASS: 20 18 8 12 24 25 30 PASS: 18 12 8 20 24 25 30 PASS: 12 8 18 20 24 25 30 PASS: 8 12 18 20 24 25 30 SORTED: 8 12 18 20 24 25 30
Complexity
Building the heap bottom-up costs O(n) (a tighter bound than the obvious O(n log n)). Each of the n−1 extractions costs O(log n). Total O(n log n) in every case, O(1) extra space.
Advantages and disadvantages
| Advantages | Disadvantages |
|---|---|
| Guaranteed O(n log n), in-place | Not stable |
| No recursion needed | Poor cache locality, often slower than quick sort |
Common mistakes
- Starting the build loop at index 0 instead of the last internal node.
- Sifting down into the already-sorted part (forgetting to shrink the heap size).
- Mixing 0-based and 1-based child formulas.
Asked in KTU exams (1)
Quick check — can you get them all?
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
- Build max-heap (O(n)), then n−1 × (swap root to end + heapify).
- O(n log n) all cases, in-place, unstable.
References
- Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — Ch. 7 (Sorting), Ch. 8 (Hashing) §7.6
- Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, 3/e — Ch. 2, 6, 7, 8, 11 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)