Skip to content
Azhimathi Mayam logoDSA Study HubPCCST303 · KTU · S3
Module 4 · syllabusAsked 1× in KTU papersChecked by code · teacher review pending

Heap sort

Build a max-heap, then repeatedly move the root (maximum) to the end.

Syllabus says: “Heap Sort”

On this page · 16 sections
ormakkurippu ✎
Never-forget card

BUILD a max-heap (O(n)), then n − 1 times: SWAP root with the last, SHRINK the heap, SIFT DOWN.

Picture it

A tournament: the winner (max) is crowned and leaves; the remaining players replay just a few matches to find the next winner.

Write this in the exam

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

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

  1. 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.
  2. Sort: swap the root with the last heap element (the maximum is now final), shrink the heap by one, and Heapify(0).
Pro tip

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

Worked example: 4, 10, 3, 5, 1checked by code
Input4 10 3 5 1
Max-heap built10 5 3 4 1
After extraction 15 4 3 1 10
After extraction 24 1 3 5 10
After extraction 33 1 4 5 10
After extraction 41 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 ◀ ▶.

Loading visualizer…

Algorithm / pseudocode

Heap sort
  1. 1HeapSort(a, n)
  2. 2for i ← ⌊n/2⌋ − 1 down to 0: Heapify(a, i, n)
  3. 3for end ← n − 1 down to 1
  4. 4swap a[0], a[end] // max goes to its final place
  5. 5Heapify(a, 0, end)
  6. 6Heapify: largest ← max of a[i], a[2i+1], a[2i+2] (within size)
  7. 7if largest ≠ i: swap a[i], a[largest]; continue at largest
  8. 8else stop
  9. 9end

C implementation

heap_sort.ctested ✓ 132/132 cases
C
/* 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

Open in the Code Lab →

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

AdvantagesDisadvantages
Guaranteed O(n log n), in-placeNot stable
No recursion neededPoor 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?

Question 1

Q1.Heap sort time in the worst case?

Question 2

Q2.Is heap sort stable?

Question 3

Q3.Max-heap of 20, 12, 30, 25, 18, 8, 24 (bottom-up)?

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)