Sorting Algorithms · 6 of 10

Heap Sort tutorial

Builds a max heap and repeatedly moves its root to the sorted suffix. Learn the concept, implement it from scratch, and apply it with Python standard library.

Category
Selection sort
Core idea
Time: Θ(n log n) · Space: Θ(1)
Typical use
In-place sorting with a guaranteed n log n upper bound.
Practical tool
Python standard library

What is Heap Sort?

Heap Sort is a selection sort technique. Builds a max heap and repeatedly moves its root to the sorted suffix. Its central idea is summarized by Time: Θ(n log n) · Space: Θ(1).

This guide connects theory to practice. You will trace the input, intermediate process, and output; decode the notation; run a dependency-light implementation; then repeat the workflow with Python standard library and evaluate the result.

By the end of this tutorial, you will be able to

  • Explain when Heap Sort is appropriate and what assumptions it makes.
  • Read its mathematical notation or complexity statement without guessing what the symbols mean.
  • Follow and modify a from-scratch Python implementation.
  • Build a practical workflow with Python standard library and choose useful evaluation checks.

Prerequisites and tools

You do not need an advanced software stack. Start with a recent Python environment and the fundamentals below, then install only the packages used by the practical example.

  • Comfort with Python lists, loops, functions, comparisons, and index manipulation.
  • An understanding of input size n, time complexity, auxiliary space, and algorithm stability.
  • The educational function from this page when running the benchmark tutorial.
LanguagePython 3
Primary libraryPython standard library
Learning modeFrom scratch + library

How Heap Sort works

  1. 1

    Input

    An unordered array of comparable values.

  2. 2

    Prepare and configure

    Check shapes, value ranges, ordering assumptions, missing values, and the parameters that control the algorithm’s behavior.

  3. 3

    Algorithm process

    Restore the heap after each root extraction so the next maximum rises to the top.

  4. 4

    Output

    The same values arranged from smallest to largest.

  5. 5

    Validate

    Track the heap invariant after every extraction.

Formula and intuition

Time: Θ(n log n) · Space: Θ(1)

Building the heap is linear, followed by n logarithmic extractions; the array stores the heap in place.

The notation captures the main operation or complexity statement behind Heap Sort. Read it together with the symbol key above and the step-by-step process in this guide.

When to use Heap Sort

In-place sorting with a guaranteed n log n upper bound.

Learning tip

Change one parameter at a time in the interactive lesson, replay the animation, and connect the visible change to the input, process, and output described above.

Heap Sort from scratch in Python

This dependency-light example emphasizes the algorithm’s mechanics so each important step remains visible.

PythonEducational implementation
def heap_sort(values):
    a = values[:]
    def sift(root, end):
        while 2 * root + 1 < end:
            child = 2 * root + 1
            if child + 1 < end and a[child] < a[child + 1]:
                child += 1
            if a[root] >= a[child]:
                return
            a[root], a[child] = a[child], a[root]
            root = child
    for root in range(len(a)//2 - 1, -1, -1):
        sift(root, len(a))
    for end in range(len(a) - 1, 0, -1):
        a[0], a[end] = a[end], a[0]
        sift(0, end)
    return a
How to use this example

Run it once unchanged, inspect the output, and then alter one input or parameter. The compact implementation is designed for learning; use the tested library workflow below for real projects.

Build Heap Sort with Python standard library

Use the educational implementation above to study this algorithm, then compare it with Python’s production-grade stable sorted() baseline.

Recommended environment

JupyterLab, Google Colab, or VS Code

Create an isolated virtual environment for a local project, or paste the cells into a hosted notebook. Pin package versions before deploying a reproducible application.

Verify your Python installation python --version
  1. Prepare the data.An unordered array of comparable values. Validate its shape, type, range, and ordering before training or execution.
  2. Configure the algorithm.Begin with explicit, conservative parameters and a fixed random seed whenever the library supports one.
  3. Fit or execute.Restore the heap after each root extraction so the next maximum rises to the top.
  4. Inspect the result.The same values arranged from smallest to largest. Then apply the evaluation checks in the next section.
PythonPython standard library workflow
from random import Random
from timeit import timeit

rng = Random(7)
values = [rng.randrange(10_000) for _ in range(250)]
expected = sorted(values)
result = heap_sort(values)
assert result == expected
assert values != expected  # the educational function leaves its input unchanged

elapsed = timeit(lambda: heap_sort(values), number=100)
baseline = timeit(lambda: sorted(values), number=100)
print("educational implementation:", elapsed)
print("Python sorted baseline:", baseline)

API details and version-specific options: official Python standard library reference →

How to evaluate the result

A successful run is not enough. Evaluate the output against the intended use, compare it with a simple baseline, and preserve a genuinely unseen test case whenever the task involves learned parameters.

  • Track the heap invariant after every extraction.
  • Validate empty, one-item, duplicate-heavy, ordered, reversed, and random inputs against sorted().
Reproducibility check

Record the data version, package versions, parameters, random seeds, and evaluation procedure. Re-run the same workflow before publishing a benchmark or deploying a model.

Pitfalls and how to avoid them

These failure modes are common in tutorials and production systems. Treat them as review questions, not just after-the-fact debugging advice.

  • It is in-place but generally not stable and may have weaker cache locality.
  • Microbenchmarks require repeated runs and representative input distributions.
  • Prefer sorted() or list.sort() in production unless this specific algorithm is a deliberate requirement.

Before using Heap Sort in a project

  • State the supported value types, ordering rule, stability requirement, and mutation behavior.
  • Test empty, singleton, duplicate-heavy, sorted, reversed, and randomized inputs.
  • Measure comparisons, writes, auxiliary memory, and elapsed time on relevant distributions.
  • Validate every result against Python’s trusted sorted() baseline.
  • Prefer the standard library in production unless a specialized algorithm is required.

Official documentation and next steps

Primary software reference Python standard library

Use the official documentation to confirm supported parameters, current defaults, input requirements, and version changes.

Read official documentation →

This guide is an educational introduction, not a substitute for domain validation. For consequential applications, review the source documentation, test against representative data, and involve a subject-matter expert.

See Heap Sort in motion

Open the interactive lesson to adjust parameters, scrub through the process, replay the animation, and compare the explanation with the Python code.

Launch visualization →