AlgoViz

Heapify

medium 16 min

Heapify is how a binary heap repairs itself.

Where it shows up

The same pattern appears across everyday software.

  • Python heapq and priority queues

    heapq.heapify, heappush and heappop are exactly build-heap, sift up and sift down on a plain list. queue.PriorityQueue and asyncio's timer scheduling sit on top of them.

  • Heap sort and introsort

    Heap sort's first phase is the O(n) bottom-up build, and every extraction is one sift down. C++ std::sort falls back to it (via std::make_heap and std::pop_heap) when quick sort recurses too deep.

  • Operating system and network schedulers

    Timer wheels and job queues keep deadlines in a heap: a new job sifts up, the next job to run is popped and the heap sifts down.

  • Graph algorithms

    Dijkstra's shortest paths and Prim's minimum spanning tree pull the closest vertex from a min-heap. Lowering a vertex's distance is a decrease-key, which is a sift up.

  • Top-k and streaming medians

    Leaderboards keep a size-k min-heap of the best scores; a running median keeps a max-heap and a min-heap. Each new value costs one sift.

  • Event-driven simulation

    Simulators store future events by timestamp in a heap. Loading the initial events with one heapify is O(n) instead of O(n log n).