Heap

A Heap is a specialized tree-based data structure that satisfies the heap property. In a binary heap, the parent node is either greater than or equal to (max-heap) or less than or equal to (min-heap) its children. Heaps are commonly used to implement priority queues.

Heap Visualization

Heap Visualizer • V3 Ultra Premium

Cinematic Heap Builder

Build and inspect a Min Heap with synchronized code, reactive visuals, motion feedback and sound.

Step

0/0

Progress

0%

Nodes

0

Speed

1.0x

Playback Controls

Step-by-step cinematic execution

0%

Playback speed1.0x

Run the heap builder to begin.

Heap Array

Index-based binary tree representation

Synced Algorithm Panel

Live execution focus

1buildHeap(arr):
2 for i = floor(n/2)-1 down to 0:
3 heapify(arr, i)
4
5heapify(arr, i):
6 best = i
7 left = 2*i + 1
8 right = 2*i + 2
9 compare left child
10 compare right child
11 if best != i:
12 swap(arr[i], arr[best])
13 heapify(arr, best)
14
15done

Complexity

Time Complexity: O(log n) insert, O(log n) delete, O(1) peek
Space Complexity: O(n)

Pseudocode

class Heap:
  function insert(value):
    add value to the end of the array
    heapifyUp()
  
  function extractRoot():
    root = heap[0]
    move last element to root
    heapifyDown()
    return root
  
  function heapifyUp():
    while parent violates heap property:
      swap with parent
  
  function heapifyDown():
    while child violates heap property:
      swap with appropriate child