Skip to content

Building a heap

storing

Level 2 of 3

Also called Heapify, Floyd's method and Bottom-up heap construction.

fresh numbers

The test's questions that a run answers, asked again on new numbers whenever you like. The answer, its working and the reason for every other choice come from building a heap's own run on the numbers shown.

choose one

question 1

On which of these rows does building a heap make no swap at all?

the answer, and why

the answer is A

Every parent is at least as big as its children, 91 over 58 and 73, 58 over 12 and 44, 73 over 60 and 29. So every sift stops at once.

91587312446029911582733124445606297
91, 58, 73, 12, 44, 60, 29 as a tree. Each marked parent is at least as big as its children.

if you chose another

  • 60 at place 5 is bigger than its parent, 58, so 58 swaps down.
  • 91 at place 2 is bigger than the top, 58, so 58 swaps down.
  • 60 at place 6 is bigger than its parent, 58, so 58 swaps down.

new numbers

question 2

Each row holds the same six numbers. On which does building a heap make the most comparisons?

the answer, and why

the answer is A

27 at the top swaps with 62, then sinks into place 2, which has two children, for another round of 2. That makes 7. The others cost 6, 5 and 6.

sift at placeABCD
31111
22222
14323
in all7656
Each row's comparisons, sift by sift. Place 3 has one child.

if you chose another

  • Smallest first swaps the most, but costs 6. 15 sinks into place 3, which has one child, so its second round compares once.
  • That is a heap already, the cheapest, 5.
  • 59 sinks into place 3, which has one child, so its second round compares once. 6 in all.

new numbers