Min-Heap Visualizer
Select an action
Logs
No operations yet
Notes
Min-Heap: Complete binary tree. Each parent is less than or equal to its children.
Insert: Traverses from root to insert point, then animates each bubble-up swap step.
Extract Min: Traverses from root down, then animates each bubble-down swap step.
Peek Min: Inspects root, highlights for 3 seconds.
Heap limit: 12 (simulates overflow)
Overflow and underflow events are visually shown.
Controls are disabled during animation for safety.
Try inserting random values and see rebalancing!
Implementation (TypeScript)
class MinHeap {
private heap: number[] = [];
insert(val: number) {
this.heap.push(val);
let idx = this.heap.length - 1;
while (idx > 0) {
const parent = Math.floor((idx - 1) / 2);
if (this.heap[parent] <= this.heap[idx]) break;
[this.heap[parent], this.heap[idx]] = [this.heap[idx], this.heap[parent]];
idx = parent;
}
}
extractMin(): number | undefined {
if (this.heap.length === 0) return undefined;
if (this.heap.length === 1) return this.heap.pop();
const min = this.heap[0];
this.heap[0] = this.heap.pop()!;
let idx = 0, n = this.heap.length;
while (true) {
let left = 2 * idx + 1, right = 2 * idx + 2, smallest = idx;
if (left < n && this.heap[left] < this.heap[smallest]) smallest = left;
if (right < n && this.heap[right] < this.heap[smallest]) smallest = right;
if (smallest === idx) break;
[this.heap[smallest], this.heap[idx]] = [this.heap[idx], this.heap[smallest]];
idx = smallest;
}
return min;
}
peek(): number | undefined { return this.heap[0]; }
clear() { this.heap = []; }
}About Heaps
A heap is a complete binary tree with the min-heap or max-heap property.
Applications:
- Priority queues
- Dijkstra's algorithm
- Heap sort
- Event scheduling
Min-Heap operations:
- insert(value): Add and bubble up
- extractMin(): Remove root and bubble down
- peek(): Inspect root
Heaps are often implemented as arrays for efficiency.