Data Structures · Visualization

Heap Construction: Introduction

Heap Construction

A heap is an array pretending to be a nearly-complete binary tree: children of index i live at 2i+1 and 2i+2. Time: O(n) bottom-up vs O(n log n) repeated insert. Space: O(1) extra — built in place.

Big-O: Bottom-up build O(n); decrease-key O(log n).

Heap Construction: Introduction

Heap Construction

A heap is an array pretending to be a nearly-complete binary tree: children of index i live at 2i+1 and 2i+2. Inserting one by one costs O(n log n), but building from a full array works bottom-up — small subtrees are already heaps, so each sift-down travels only a short distance, for O(n) total.

How Heap Construction: Introduction Works

  1. Lay the values out as-is; index math gives the tree shape for free.
  2. Start from the last parent (index n/2 − 1) and move backwards.
  3. Sift each node down: swap with the larger child (max-heap) until order holds.
  4. When the root is sifted, the whole array is a valid heap.

Heap Construction: Introduction Worked Example

Input: Build a max-heap from [4, 10, 3, 5, 1]

  1. Last parent is index 1 (10): children 5, 1 — already ordered.
  2. Index 0 (4): larger child is 10 → swap → [10, 4, 3, 5, 1].
  3. Node 4 at index 1: larger child 5 → swap → [10, 5, 3, 4, 1].
  4. Root done: valid max-heap in 2 swaps.

Output: Max-heap: [10, 5, 3, 4, 1]

📖 Introduction: this is an overview of the topic, so there's nothing to run here. Pick an operation from the side menu to see a live, step-by-step animation.
Heap Construction: Introduction
Bottom-up heapify beats repeated insert: O(n), in place.
7
0
2
1
9
2
4
3
1
4
8
5
Swapping pair
Heap Construction: Introduction
Press ▶ Run to watch it step by step.
Python · Heap Construction in Code
def build_heap(a):
    for i in range(len(a) // 2 - 1, -1, -1):
        sift_down(a, i)   # small subtrees first

arr = [7, 2, 9, 4, 1, 8]  # O(n) total
# example: intro on [4, 10, 3, 5, 1]

Heap Construction: Introduction Time & Space Complexity

TimeO(n) bottom-up vs O(n log n) repeated insert
SpaceO(1) extra — built in place

When to Use Heap Construction: Introduction

  • Heap-sort's first pass and priority-queue bulk loading
  • Seeding schedulers with a whole batch of jobs at once

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.