Skip to main content

Heap tree insertion and heap sort

Short answer

Insert each value at the end and bubble up: final max-heap array is 29,28,25,23,18,14,11,12,21. Sort by repeatedly moving root to end and sifting down: final ascending order 11,12,14,18,21,23,25,28,29. Overall time O(n log n).

Create a heap tree showing each insertion steps for the following data. Use the same heap tree to sort the data showing each intermediate steps: 14, 12, 25, 18, 21, 29, 11, 28, 23.

A max-heap is built by inserting keys one at a time at the next free position (end of the array) and moving the key up (swapping with its parent) while it is larger than its parent.

Part 1: insertion of 14, 12, 25, 18, 21, 29, 11, 28, 23

StepInsertArray (heap) after stepMoves
11414none
21214, 12none
32525, 12, 1425↔14
41825, 18, 14, 1218↔12
52125, 21, 14, 12, 1821↔18
62929, 21, 25, 12, 18, 1429↔14, 29↔25
71129, 21, 25, 12, 18, 14, 11none
82829, 28, 25, 21, 18, 14, 11, 1228↔12, 28↔21
92329, 28, 25, 23, 18, 14, 11, 12, 2123↔21

Final heap (array positions 1–9):

level 0:  29
level 1:  28   25
level 2:  23   18   14   11
level 3:  12   21
Tree:          29
            /      \
          28        25
         /  \      /  \
       23    18   14   11
      /  \
    12    21

Part 2: heap sort using the same heap

Swap the root with the last element of the heap, reduce the heap size, and sift the new root down.

PassMax moved to endHeap part after re-heapifySorted part
129 (last position 9)28, 23, 25, 21, 18, 14, 11, 1229
228 (last position 8)25, 23, 14, 21, 18, 12, 1128, 29
325 (last position 7)23, 21, 14, 11, 18, 1225, 28, 29
423 (last position 6)21, 18, 14, 11, 1223, 25, 28, 29
521 (last position 5)18, 12, 14, 1121, 23, 25, 28, 29
618 (last position 4)14, 12, 1118, 21, 23, 25, 28, 29
714 (last position 3)12, 1114, 18, 21, 23, 25, 28, 29
812 (last position 2)1112, 14, 18, 21, 23, 25, 28, 29
––(empty)11, 12, 14, 18, 21, 23, 25, 28, 29

Sorted data (ascending): 11, 12, 14, 18, 21, 23, 25, 28, 29

Insertion takes O(log n) per key; the sorting phase takes n − 1 sift-downs of O(log n), so the total is O(n log n).

✓ Answer checked by Claude Opus 5.5 (high effort)

All Data Structure and Algorithm chapter 7 questions →