Linear-Time Binary Heap Construction

Explain why bottom-up heapification takes linear time by summing the heights of the subtrees actually repaired.

Source
Anbloq
Language
English
Created
Updated
Chapters
2
Reading time
1 min
In this article2 chapters
  1. Start where children are already heaps
  2. Most nodes have little room to move

Start where children are already heaps

Represent a binary heap in breadth-first array order. For a zero-based index \(i\), its children, when present, are \(2i+1\) and \(2i+2\). Leaves already satisfy the heap condition. Process internal nodes in reverse order. Sifting a key down swaps it with its smaller child in a min-heap until it is no larger than both children. When this starts, each child subtree is already a heap.

Most nodes have little room to move

Although the root can move logarithmically far, about half of all nodes are leaves. In a perfect tree, the number of nodes of height at least \(h\) is at most \(n/2^h\), up to constant factors. Summing this count over \(h\ge1\) bounds total descent work by \(O(n)\), also for the complete tree used by an array heap. Repeated insertions only give the simpler \(O(n\log n)\) worst-case construction. Indexed heaps add inverse positions for priority changes, and amortized aggregate analysis uses a related technique of summing the work that can really occur.[1]

References

  1. MIT OpenCourseWare, Introduction to Algorithms: Lecture Notes ↩