Intermediate 25 min

Binary Heaps

A binary heap is a complete binary tree that satisfies the heap property.

Heap Property

Max Heap: Parent ≥ Children (for all nodes) Min Heap: Parent ≤ Children (for all nodes)

For heap sort, we use a max heap.

Array Representation

Heaps are stored in arrays. For a node at index i:

  • Left child: 2i + 1
  • Right child: 2i + 2
  • Parent: ⌊(i-1)/2⌋

Visual Example

Interactive Diagram

This interactive diagram requires JavaScript to be enabled.

9 Index 0 5 Index 1 8 Index 2 Array: [9, 5, 8] Index: 0 1 2 Parent(1) = 0, Left(0) = 1, Right(0) = 2

Steps:

  1. Binary heap as a tree structure
  2. Same heap stored in an array

Complete Binary Tree

A complete binary tree is filled from left to right at each level. This allows efficient array storage.

Heap Operations

• Maintain heap property • Compare with children • Swap if needed • O(log n) time

What’s Next?

Now that you understand heaps, let’s learn the heapify operation.