A topic in the Open Knowledge Graph — a free, open map of 15,290 topics and the order to learn them in.

Heapsort

College Depth 86 in the knowledge graph ☐ I know this ☆ Set as goal
2topics build on this
459prerequisites beneath it
See this on the map →
Heaps and Priority QueuesTime and Space Complexity→→Sorting Lower Bounds and Non-Comparison Sorts
sorting heapsort heap in-place

Core Idea

Heapsort sorts an array by first building a max-heap in O(n) time, then repeatedly extracting the maximum element and placing it at the end of the array. The full algorithm runs in O(n log n) time and sorts in-place using O(1) auxiliary space. Heapsort provides guaranteed O(n log n) worst-case performance unlike quicksort. However, it exhibits poor cache performance and is not stable.

How It's Best Learned

Implement heapsort by reusing the heap operations from a prior heap implementation. Trace through both phases (heapify the entire array, then repeatedly extract-max) on a 7-element example.

Common Misconceptions

Explainer

You already know how a max-heap works: a complete binary tree where every parent is at least as large as its children, supporting insert and extract-max in O(log n) time. Heapsort exploits this structure to sort an array in-place without allocating additional memory. The algorithm has two distinct phases, and understanding why each phase has the complexity it does is the key insight.

Phase 1: Build the heap. Given an unsorted array, you transform it into a valid max-heap using a bottom-up process called heapify. Starting from the last non-leaf node and working toward the root, you "sift down" each node to restore the heap property. The critical insight — and a common source of confusion — is that this runs in O(n), not O(n log n). The reason is that most nodes are near the bottom of the tree and have very little distance to sift. Roughly half the nodes are leaves (zero work), a quarter are one level up (at most one swap), an eighth are two levels up, and so on. The sum of this geometric series converges to O(n).

Phase 2: Repeated extraction. Once the array is a valid max-heap, the largest element sits at index 0. You swap it with the last element of the unsorted portion, shrink the heap by one, and sift-down the new root to restore the heap property. Each extraction takes O(log n), and you perform n-1 of them, giving O(n log n) for this phase. The total is O(n) + O(n log n) = O(n log n).

Heapsort's greatest practical strength is its guaranteed O(n log n) worst-case performance — unlike quicksort, which degrades to O(n²) on adversarial inputs. It also sorts in-place with O(1) extra space, unlike merge sort which typically requires O(n) auxiliary storage. The tradeoff is cache performance: heapsort jumps between distant array indices during sift-down operations (parent at index i, children at 2i+1 and 2i+2), causing frequent cache misses. In practice, this makes heapsort slower than quicksort on most real-world data despite its better worst-case guarantee. For this reason, many standard library sort implementations use a hybrid like introsort — quicksort by default, falling back to heapsort only when recursion depth suggests a worst-case input.

Practice Questions 5 questions

Prerequisite Chain

Understanding Zero → The Number Zero → Counting to Five → Counting to 10 → Counting to 20 → Counting a Set of Objects Up to 20 → Cardinality: The Last Number Counted → Matching Numerals to Quantities → Subitizing Small Quantities → Addition Within 10 → Number Bonds to 10 → Addition Within 20 → Doubles and Near Doubles → Doubles Facts Within 10 → Near Doubles Facts Within 20 → Mental Math Strategies for Addition → Mental Math: Adding and Subtracting Tens → Addition Within 100 → Repeated Addition as Multiplication → Multiplication as Equal Groups → Multiplication: Arrays → Basic Multiplication Facts (0s, 1s, 2s, 5s, 10s) → Multiplication Facts Within 100 → Division as Equal Sharing → Division as Grouping (Measurement Division) → Division: Grouping (Repeated Subtraction) Model → Division: Fair Sharing Model → Division as Equal Sharing → Division as Grouping → Basic Division Facts → Division Facts Within 100 → Multiplication and Division Fact Families → Relationship Between Multiplication and Division → Division Facts as Inverse of Multiplication → Remainders and Quotients in Division → Division Word Problems → Multi-Step Word Problems → Solving Multi-Step Word Problems → Multiplication Word Problems → Division Word Problems → Introduction to Long Division → Factors and Multiples → Prime and Composite Numbers → Equivalent Fractions → Relating Fractions and Decimals → Decimal Place Value → Integers and the Number Line → Comparing and Ordering Integers → Absolute Value → Adding Integers → Subtracting Integers → Multiplying Integers → Introduction to Exponents → Order of Operations → Integer Order of Operations → Variable Expressions → The Distributive Property → Variables and Expressions Review → Introduction to Polynomials → Adding and Subtracting Polynomials → Multiplying Polynomials → Factorial → Permutations → Combinations → Counting Principles: Addition and Multiplication Rules → Introduction to Graph Theory → Propositional Logic Foundations → Logical Equivalences → Boolean Algebra → Boolean Type and Truth Values → Comparison Operators and Boolean Tests → Logical Operators and Boolean Algebra → Conditional Statements → Defining and Calling Functions → Functions: Decomposing Problems → Function Parameters and Argument Passing → Return Values → Variable Scope → Introduction to Classes → Objects and Instances → Methods and Attributes → Algorithm Design Basics → Asymptotic Notation: Big-O, Big-Omega, Big-Theta → Big-O Notation and Complexity Analysis → Time and Space Complexity → Heaps and Priority Queues → Heapsort

Longest path: 87 steps · 459 total prerequisite topics

Prerequisites (2)

Leads To (1)