Chapter 11 · Simulation

Binary Heap Simulator

← Chapter 11

Array representation

Sample max-heap loaded. Choose an operation.

Binary Heap Simulator

A binary heap is a complete binary tree stored in an array. In a max-heap no parent is smaller than its children (in a min-heap, no parent is larger), so the largest (smallest) value sits at the root.

Controls

  • Heap type switches between max-heap and min-heap.
  • Insert adds a value; Remove Root deletes the root; Peek just reads it.
  • Build Heap builds a heap from the comma-separated values; Random fills the heap with random values; Heap Sort sorts the array in place.
  • Reset empties the heap; Cancel stops the animation and puts the heap back the way it was.

Index arithmetic (0-based)

parent(i) = ⌊(i − 1) / 2⌋, left(i) = 2i + 1, right(i) = 2i + 2.

Operations

  • Insert: the value goes into the first free slot at the end and moves up while it beats its parent (up-heap).
  • Remove: the last element moves to the root, then sinks by swapping with the better child (down-heap).
  • Building a heap (bottom-up): every internal node from ⌊n/2⌋ − 1 down to 0 is sunk in turn.
  • Heap sort: swap the root with the last heap element, shrink the heap by one, sink the new root; repeat.

Complexity

OperationTime
peek at the rootO(1)
insert, removeO(log n)
build a heapO(n)
heap sortO(n log n), in place