Visualize Floyd's O(N) heap construction algorithm. Watch how sift-down from the last non-leaf builds a valid heap faster than N individual insertions.
About this algorithm
Build heap turns an unsorted array into a valid heap in place. Instead of inserting the values one at a time, it treats the array as a complete tree and sifts down every node that has a child, starting from the last one and working back to the root. The whole job takes O(N), less than the O(N log N) of N separate inserts.
Use it whenever every value is known before the heap is needed: the first phase of heap sort, setting up a priority queue from a ready list of tasks, or Python's heapq.heapify. Use insert, as on the min heap and max heap pages, when values arrive one by one over time. Building only arranges the heap rule, where each parent beats its children; to get sorted output you still extract the values one by one, which is what heap sort does next.
Every index from floor(n / 2) to the end is a leaf, and a single node with no children is a valid heap. There is nothing to do there.
The last node with a child is at index floor(n / 2) - 1. For 7 values that is index 2.
For i from that last parent down to 0, sift the value at i down: swap it with its smaller child (this page builds a min heap) until it is no larger than either child. By the time i is reached, both of its subtrees are already heaps, so one sift down fixes the subtree rooted at i.
Once index 0 has been sifted, the whole array follows the heap rule.
The page's first preset is [5, 3, 8, 1, 9, 2, 7]. With seven values the last parent is index 2, which holds 8 with children 2 and 7: swap with 2, giving [5, 3, 2, 1, 9, 8, 7]. Index 1 holds 3 with children 1 and 9: swap with 1, giving [5, 1, 2, 3, 9, 8, 7]. Index 0 holds 5 with children 1 and 2: swap with 1, and at index 1 the 5 meets children 3 and 9, so swap with 3. The result is [1, 3, 2, 5, 9, 8, 7] after 4 swaps. The other two presets finish as [1, 4, 3, 10, 7, 12, 15] after 4 swaps and [2, 8, 4, 11, 13, 6, 9] after 3.
A sift down costs at most the height of the node it starts from. Half the nodes are leaves with height 0, a quarter have height 1, an eighth height 2, and so on. Adding n/4 × 1 + n/8 × 2 + n/16 × 3 and onward comes to no more than n swaps. Inserting one by one does the opposite: each new value starts at the bottom, and the many values near the bottom may each climb about log N levels, which is O(N log N).
Time: most nodes sit near the bottom and sift only a level or two, so the swaps across the whole array add up to at most about N. Space: the array is rearranged in place, and an iterative sift down needs only a few index variables.