Skip to content

Binary heap

storing

Level 2 of 3

Also called Priority queue and Min-heap.

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 binary heap's own run on the numbers shown.

choose one

question 1

The heap drawn was made by putting in 40, 25, 33, 18 and 29; its letters show the order each number came in. Put in 12. What is the row then?

123451825334029d18b25c33a40e29
the answer, and why

the answer is A

12 goes in at place 6, under 33. It is smaller, so they swap. Now under 18, it is smaller again, so they swap. At the top, it stays.

  1. step 18 of 24

    182533402912

    Put 12 at the end of the row, in place 6.

    comparisons: 0

  2. step 20 of 24

    182512402933

    Swap them: 12 climbs above 33.

    comparisons: 1

  3. step 22 of 24

    122518402933

    Swap them: 12 climbs above 18.

    comparisons: 2

  4. step 23 of 24

    122518402933

    12 is at the top, so it stays.

    comparisons: 2

12 put at place 6 climbs above 33, then above 18, to the top. 2 comparisons.

if you chose another

  • That stops after one swap, but 12 is still smaller than 18 above it.
  • That leaves 12 where it was put, under 33, which is bigger.
  • That is the whole row in order. A heap only swaps 12 up its way to the top.

new numbers

question 2

How many comparisons do these operations make on an empty heap? 16, 9, 21, 4, then one take.

the answer, and why

the answer is C

16 compares nothing. 9 compares with 16 and climbs to the top. 21 compares with 9 and stays. 4 climbs past 16 and 9, two. The take moves 16 to the top, which meets 9 and 21, two more. 16 swaps below 9, has nothing under it, and stops.

operationcomparisons
put 160
put 91
put 211
put 42
take2
in all6
Each operation of 16, 9, 21, 4 and a take, in comparisons.

if you chose another

  • That counts the puts only. The take compares too.
  • That counts a comparison each time a number is at the top, but nothing is above it to compare with.
  • That counts one comparison for the take. 16 meets both children of the top.

new numbers

question 3

Each list puts five numbers into an empty heap. Which makes the fewest comparisons?

the answer, and why

the answer is D

Smallest first, each number is no smaller than the one above it, so it stays after one comparison. That costs 0, 1, 1, 1 and 1, 4 in all. The others cost 6, 5 and 5.

putabcd
1st0000
2nd1111
3rd1111
4th1221
5th1212
in all4655
Each list's comparisons, put by put.

if you chose another

  • Biggest first, each number climbs all the way to the top, one comparison a level. It costs 6.
  • 33 climbs over 61, and 48 climbs over 61, then stops under 33. It costs 5.
  • 33 climbs over 61, and 48 climbs over 75, then stops under 33. It costs 5.

new numbers