Heaps
Imagine a VIP lounge where the most important guest is always at the front of the line. When that guest leaves, the next most important person instantly moves to the front. New arrivals politely shuffle up or stay back based on their importance. That's a heap — a priority queue where the most urgent item is always instantly accessible.
Technically, a heap is a complete binary tree stored compactly in an array, satisfying one simple rule:
- Min-Heap: every parent ≤ its children (root holds the minimum)
- Max-Heap: every parent ≥ its children (root holds the maximum)
The tree is "complete" — all levels are fully filled except possibly the last, which fills left to right. This lets us use a plain array with no pointers: for node at index i, its left child is at 2i+1, right child at 2i+2, and parent at (i-1)//2.
← → arrow keys to step · click elements to interact
Heap Operations
Sift Up — after inserting
Insert a new value at the end of the array (next open position in the tree). Then compare it with its parent. If the heap property is violated, swap with parent and repeat. This "sift up" (or "bubble up") continues until the property holds or the element reaches the root. At most log n swaps — one per level.
Sift Down — after extracting
The root (min/max) is what we want. Remove it, then move the last element to the root to keep the array compact. Now sift down: compare with both children, swap with the smaller child (min-heap), repeat until the heap property holds. Again, at most log n swaps.
Build Heap in \(O(n)\)
Inserting n elements one by one costs \(O(n \log n)\). But there is a smarter way: start from the last non-leaf node (index n//2 - 1) and sift down each node toward the leaves. The math works out that the total work is \(O(n)\) — this is the heapify algorithm used by heap sort.
Complexity
K Smallest Elements
Quick check
Continue reading