A Heaps
09 — Data Structures
The priority queue's engine

The Heap

A tree that always knows its smallest (or largest) value. Insert and extract in O(log n) — the structure behind every priority queue and heapsort.

A binary heap is a complete binary tree — every level filled left to right — with one rule, the heap property. In a min-heap, every parent is smaller than or equal to its children, so the smallest value is always at the root. (A max-heap flips it: the largest sits on top.) Because the tree is complete, it packs perfectly into a plain array: a node at index i has children at 2i+1 and 2i+2. Insert by adding at the end and bubbling up; extract the root by moving the last item up and sinking it down. Both touch only one path — O(log n).

Try it in 3D

The orbs form a complete tree; the strip below shows the same heap as its backing array. Insert and watch a value bubble up; extract and watch the new root sink down.

Drag to rotate — scroll to zoom
array ?
mode
Press an operation above.ready
Root (min/max) Inserted / moving Comparing Swapping

The operations

Every change touches just one root-to-leaf path, so the cost is the tree's height — O(log n).

Cost cheat sheet

A heap is unbeatable for "give me the min/max repeatedly" — but it is not sorted, so arbitrary search is still O(n).