Explore heap operations with an interactive priority queue visualization. See how parent-child ordering changes during insertion and removal.
Visualize and understand binary heap operations like insertion, extraction, and heapify.
Interactive Heap Visualization
Heap Operations Explained
Heap Insertion
Goal: Add a new element while maintaining the heap property (min-heap or max-heap).
Algorithm:
- Add the new element to the bottom level of the heap (end of the array).
- Compare the added element with its parent.
- If they are in the wrong order (e.g., child < parent in min-heap), swap them.
- Repeat steps 2 and 3 ("sift-up" or "bubble-up") until the heap property is restored or the root is reached.
function insert(heap, value, isMinHeap) {
heap.push(value);
let index = heap.length - 1;
while (index > 0) {
let parentIndex = Math.floor((index - 1) / 2);
// Condition changes based on heap type
const shouldSwap = isMinHeap
? heap[index] < heap[parentIndex]
: heap[index] > heap[parentIndex];
if (!shouldSwap) break; // Correct position found
// Swap
[heap[index], heap[parentIndex]] = [heap[parentIndex], heap[index]];
index = parentIndex; // Move up
}
}Time Complexity: O(log n)