liveBook · Manning

Heapify

As explained in Grokking Data Structures

A heapify method is an operation that transforms an array of elements into a heap.

Heapify transforms an existing array into a valid heap. Unlike sorting or inserting elements one at a time, it builds the heap directly in linear time, O(n). section 10.19 section 10.22

The method builds larger valid subheaps from smaller ones:

  • Treat the arbitrary array as a binary, almost complete tree. Leaves already form valid subheaps. section 10.19
  • Visit internal nodes from the lowest level upward, fixing each possible violation by pushing the node downward. section 10.19
  • Prefer heapify over sorting or repeated insertion when the goal is simply to build a heap: those alternatives take O(n log n), while heapify takes O(n). section 10.19

Bottom-up repair

For an array represented as a binary tree, begin with the internal node at the second-to-last level. Its children are leaves, so pushing its root downward can produce a valid subheap. Continue upward until the root is repaired. section 10.19

def _heapify(self, elements):
    self._elements = elements[:]
    last_inner_node_index = self._first_leaf_index() - 1
    for index in range(last_inner_node_index, -1, -1):
        self._push_down(index)  
def _first_leaf_index(self):
    return len(self) // 2

A compact Python implementation copies the input array, finds the last internal node, and calls _push_down in reverse index order. section 10.19

How Grokking Data Structures covers it

How deep it goes
Explains bottom-up repair and linear complexity, stopping short of a formal proof.
Examples
Uses an arbitrary array represented as a binary tree and repairs internal nodes from the second-to-last level upward.
What you can do after
Build it from scratch using an array copy, reverse internal-node traversal, and push-down repair.
How it connects
Connects heapify with binary heaps, priority queues, array representations, sorting, and insertion.

Also explained in

Compare how 2 books explain heapify →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Data Structures. The section links point to the parts of the book it draws on.