Binary Heap & Heap Sort
Interactive Max/Min Heap with array vs tree dual view and sift animations.
About this tool
A binary heap is a complete binary tree stored in a plain array: the children of index i live at 2i+1 and 2i+2, and its parent at ⌊(i−1)/2⌋. In a max-heap every parent is at least as large as its children (a min-heap is the reverse), so the top element is always the maximum (or minimum). It is the standard way to implement a priority queue.
This lab draws the tree and the array side by side and animates sift-up on insert, sift-down on extract, the O(n) bottom-up heap construction, and heapsort. Switch between max-heap and min-heap to see the same operations with the order reversed.
How to use Binary Heap & Heap Sort
- Pick max-heap or min-heap. Switching rebuilds the current values into a valid heap of the new kind.
- Insert a value: it is placed at the end of the array and swapped upward while it beats its parent.
- Extract the top: the last element moves to the root and sinks down, swapping with its larger (or smaller) child.
- Run Build heap or Heapsort to watch the full algorithms step by step, with the array indices highlighted.
Examples
Insert into a max-heap
[50, 30, 40, 10, 20] insert 45
45 is appended at index 5, swaps with its parent 40 → [50, 30, 45, 10, 20, 40]
Extract max
[50, 30, 45, 10, 20, 40]
Returns 50; 40 moves to the root and sinks → [45, 30, 40, 10, 20]
Heapsort
[4, 10, 3, 5, 1]
[1, 3, 4, 5, 10] — build a max-heap, then repeatedly swap the root to the end
Implementation in five languages
The same algorithm in Python, JavaScript, Java, Go and C++. Each program is complete and runnable; the comments show what it prints.
class MinHeap:
def __init__(self):
self.a = []
def push(self, x):
a = self.a
a.append(x)
i = len(a) - 1
while i > 0: # sift up
parent = (i - 1) // 2
if a[parent] <= a[i]:
break
a[parent], a[i] = a[i], a[parent]
i = parent
def pop(self):
a = self.a
top = a[0]
last = a.pop()
if a:
a[0] = last
i, n = 0, len(a)
while True: # sift down
left, right, smallest = 2 * i + 1, 2 * i + 2, i
if left < n and a[left] < a[smallest]:
smallest = left
if right < n and a[right] < a[smallest]:
smallest = right
if smallest == i:
break
a[i], a[smallest] = a[smallest], a[i]
i = smallest
return top
def __len__(self):
return len(self.a)
h = MinHeap()
for x in [5, 3, 8, 1, 9, 2]:
h.push(x)
print(h.a) # [1, 3, 2, 5, 9, 8]
print([h.pop() for _ in range(len(h))]) # [1, 2, 3, 5, 8, 9] class MinHeap {
constructor() {
this.a = [];
}
get size() {
return this.a.length;
}
push(x) {
const a = this.a;
a.push(x);
let i = a.length - 1;
while (i > 0) { // sift up
const parent = (i - 1) >> 1;
if (a[parent] <= a[i]) break;
[a[parent], a[i]] = [a[i], a[parent]];
i = parent;
}
}
pop() {
const a = this.a;
const top = a[0];
const last = a.pop();
if (a.length > 0) {
a[0] = last;
let i = 0;
const n = a.length;
for (;;) { // sift down
const left = 2 * i + 1, right = 2 * i + 2;
let smallest = i;
if (left < n && a[left] < a[smallest]) smallest = left;
if (right < n && a[right] < a[smallest]) smallest = right;
if (smallest === i) break;
[a[i], a[smallest]] = [a[smallest], a[i]];
i = smallest;
}
}
return top;
}
}
const h = new MinHeap();
for (const x of [5, 3, 8, 1, 9, 2]) h.push(x);
console.log(h.a.join(', ')); // 1, 3, 2, 5, 9, 8
const sorted = [];
while (h.size > 0) sorted.push(h.pop());
console.log(sorted.join(', ')); // 1, 2, 3, 5, 8, 9 import java.util.ArrayList;
import java.util.List;
public class Main {
static class MinHeap {
final List<Integer> a = new ArrayList<>();
int size() { return a.size(); }
void push(int x) {
a.add(x);
int i = a.size() - 1;
while (i > 0) { // sift up
int parent = (i - 1) / 2;
if (a.get(parent) <= a.get(i)) break;
swap(parent, i);
i = parent;
}
}
int pop() {
int top = a.get(0);
int last = a.remove(a.size() - 1);
if (!a.isEmpty()) {
a.set(0, last);
int i = 0, n = a.size();
while (true) { // sift down
int left = 2 * i + 1, right = 2 * i + 2, smallest = i;
if (left < n && a.get(left) < a.get(smallest)) smallest = left;
if (right < n && a.get(right) < a.get(smallest)) smallest = right;
if (smallest == i) break;
swap(i, smallest);
i = smallest;
}
}
return top;
}
private void swap(int i, int j) {
int t = a.get(i);
a.set(i, a.get(j));
a.set(j, t);
}
}
public static void main(String[] args) {
MinHeap h = new MinHeap();
for (int x : new int[] {5, 3, 8, 1, 9, 2}) h.push(x);
System.out.println(h.a); // [1, 3, 2, 5, 9, 8]
List<Integer> sorted = new ArrayList<>();
while (h.size() > 0) sorted.add(h.pop());
System.out.println(sorted); // [1, 2, 3, 5, 8, 9]
}
} package main
import "fmt"
type MinHeap struct{ a []int }
func (h *MinHeap) Len() int { return len(h.a) }
func (h *MinHeap) Push(x int) {
h.a = append(h.a, x)
i := len(h.a) - 1
for i > 0 { // sift up
parent := (i - 1) / 2
if h.a[parent] <= h.a[i] {
break
}
h.a[parent], h.a[i] = h.a[i], h.a[parent]
i = parent
}
}
func (h *MinHeap) Pop() int {
a := h.a
top := a[0]
n := len(a) - 1
a[0] = a[n]
a = a[:n]
i := 0
for { // sift down
left, right, smallest := 2*i+1, 2*i+2, i
if left < n && a[left] < a[smallest] {
smallest = left
}
if right < n && a[right] < a[smallest] {
smallest = right
}
if smallest == i {
break
}
a[i], a[smallest] = a[smallest], a[i]
i = smallest
}
h.a = a
return top
}
func main() {
h := &MinHeap{}
for _, x := range []int{5, 3, 8, 1, 9, 2} {
h.Push(x)
}
fmt.Println(h.a) // [1 3 2 5 9 8]
var sorted []int
for h.Len() > 0 {
sorted = append(sorted, h.Pop())
}
fmt.Println(sorted) // [1 2 3 5 8 9]
} #include <iostream>
#include <utility>
#include <vector>
class MinHeap {
public:
std::vector<int> a;
bool empty() const { return a.empty(); }
void push(int x) {
a.push_back(x);
size_t i = a.size() - 1;
while (i > 0) { // sift up
size_t parent = (i - 1) / 2;
if (a[parent] <= a[i]) break;
std::swap(a[parent], a[i]);
i = parent;
}
}
int pop() {
int top = a[0];
a[0] = a.back();
a.pop_back();
size_t i = 0, n = a.size();
while (true) { // sift down
size_t left = 2 * i + 1, right = 2 * i + 2, smallest = i;
if (left < n && a[left] < a[smallest]) smallest = left;
if (right < n && a[right] < a[smallest]) smallest = right;
if (smallest == i) break;
std::swap(a[i], a[smallest]);
i = smallest;
}
return top;
}
};
int main() {
MinHeap h;
for (int x : {5, 3, 8, 1, 9, 2}) h.push(x);
for (int x : h.a) std::cout << x << ' '; // 1 3 2 5 9 8
std::cout << '\n';
while (!h.empty()) std::cout << h.pop() << ' '; // 1 2 3 5 8 9
std::cout << '\n';
} Practice on LeetCode
Classic problems that use this algorithm. Try them after working through the lab. Links open on LeetCode.
Costs
- Peek: O(1). Insert and extract: O(log n), one root-to-leaf path.
- Build heap bottom-up: O(n), because most nodes are near the bottom and sink only a short distance.
- Heapsort: O(n log n) in every case, in place, but not stable.
Where heaps are used
Schedulers and event simulations pick the next job by priority; Dijkstra’s and Prim’s algorithms pop the closest vertex; top-k queries keep a heap of size k; and merging k sorted files uses a heap of the current heads. Most languages ship one: Python heapq, Java PriorityQueue, C++ std::priority_queue.
Frequently asked questions
Everything you need to know about this tool and data security.
Why an array instead of nodes and pointers?
A heap is always a complete tree, so there are no gaps; index arithmetic replaces pointers, saves memory and is cache-friendly.
Can I search a heap quickly?
No. Finding an arbitrary value takes O(n). If you need ordered lookups, use a balanced search tree.
Why is building a heap O(n) and not O(n log n)?
Sift-down cost depends on the height below a node. Half the nodes are leaves (cost 0), a quarter have height 1, and so on; the sum converges to about 2n.
Is my data safe when using this tool?
Yes, 100% safe. This tool operates entirely inside your web browser using client-side JavaScript and WebAssembly. Your data never touches any external server.
Related Tools
Compare Bubble, Selection, Insertion, Quick, Merge, and Heap sorts in real-time.
Self-balancing binary search tree with LL, RR, LR, and RL rotation animations.
Interactive BST visualizer with insertion, deletion, and tree traversals.
Featured Projects tech-fun.net
Explore more AI & productivity tools
Nihongo GameBox
Master Japanese typing, Kana, and JLPT N5–N1 vocabulary through interactive retro arcade games.
ResumeGPT
Tailors CVs and cover letters to every job opportunity with a multi-agent LLM pipeline, job tracking, and scheduled discovery.
CollectMind
Turns your bookmarks into a searchable AI knowledge base — entirely on-device, powered by Chrome's built-in Gemini Nano.