How to use the Heap Visualizer
- 1. Enter valuesUp to 31 numbers.
- 2. Pick heap type and methodMax or min, insert one by one or heapify, and how many roots to extract.
- 3. Step throughEach swap is highlighted in the tree and the array.
How a binary heap works
A binary heap is a complete binary tree stored in an array. In a max-heap, every parent is at least as large as its children, so the largest value is always at the root; a min-heap is the reverse. With the array starting at index 0, the parent of index i is at (i − 1) ÷ 2 and its children are at 2i + 1 and 2i + 2.
- Insert: add the value at the end, then bubble up, swapping with its parent while it's bigger: O(log n).
- Extract the root: move the last item to the root, then sift down, swapping with the larger child: O(log n).
- Heapify: sift down every non-leaf node from the last one up to the root. This builds a heap in O(n).
Heaps power priority queues, Dijkstra's and Prim's algorithms, scheduling, and heap sort.
Worked example
Insert 35, 33, 42, 10, 14, 19, 27, 44, 26, 31 into a max-heap one by one. 42 bubbles above 35, and 44 bubbles all the way from the bottom to the root. The final array is [44, 42, 35, 33, 31, 19, 27, 10, 26, 14].
Heapify the same values instead and you get [44, 35, 42, 33, 31, 19, 27, 10, 26, 14]. That's a different array, but it's just as valid a max-heap with the same root. Many students are surprised the two methods disagree; both are correct, because a heap only promises the parent-child order, not one exact layout.
Set extract the root to 3 and the tool removes 44, 42 and 35 in that order, re-heaping after each. Extracting every value in turn is heap sort.
Frequently asked questions
Is a heap the same as a sorted array?
No. Only the parent-child order is guaranteed; siblings can be in any order.
What does Python's heapq give?
A min-heap. For a max-heap, push negated values.
Why is heapify O(n) and not O(n log n)?
Most nodes are near the bottom and sift down only a level or two. The total work adds up to less than 2n swaps.
Is the heap visualizer free to use?
Yes, the heap visualizer is free and costs nothing. Building your first heap shows a short form for your name and WhatsApp number one time; once that's done, this tool and every other Uncodemy tool open with no form.