Skip to main content

Heap sort on 37, 33, 26, 92, ...

Short answer

Build max-heap by heapifying from last parent: final heap array 92,86,48,33,57,22,26,25,12,37,42,18. Sorting phase repeatedly swaps max to end and re-heapifies. Final sorted list: 12,18,22,25,26,33,37,42,48,57,86,92.

Construct heap sort for the following given list with an algorithm: 37, 33, 26, 92, 57, 18, 48, 25, 12, 86, 42, 22.

Heap sort has two phases: (1) build a max-heap from the list, (2) repeatedly remove the largest element and put it at the end.

Algorithm

HeapSort(a[0..n-1])
1. for i = n/2 - 1 down to 0: Sift(a, i, n)       /* build max-heap */
2. for last = n-1 down to 1:
      swap a[0] and a[last]                       /* max goes to its place */
      Sift(a, 0, last)                            /* heap size is now 'last' */

Sift(a, i, n):   /* push a[i] down until parent >= children */
   while 2i+1 < n:
       c = index of larger child of i
       if a[c] <= a[i] stop
       swap a[i], a[c]; i = c

Phase 1: build the heap

List (index 0 to 11): 37, 33, 26, 92, 57, 18, 48, 25, 12, 86, 42, 22. The last parent is index 5 (n/2 − 1).

StepHeapify nodeArray
start–37, 33, 26, 92, 57, 18, 48, 25, 12, 86, 42, 22
1a[5]37, 33, 26, 92, 57, 22, 48, 25, 12, 86, 42, 18
2a[4]37, 33, 26, 92, 86, 22, 48, 25, 12, 57, 42, 18
3a[3]37, 33, 26, 92, 86, 22, 48, 25, 12, 57, 42, 18
4a[2]37, 33, 48, 92, 86, 22, 26, 25, 12, 57, 42, 18
5a[1]37, 92, 48, 33, 86, 22, 26, 25, 12, 57, 42, 18
6a[0]92, 86, 48, 33, 57, 22, 26, 25, 12, 37, 42, 18

Heap obtained:

level 0:  92
level 1:  86   48
level 2:  33   57   22   26
level 3:  25   12   37   42   18

Phase 2: sorting

Each pass swaps the root with the last heap element, shrinks the heap by one, and sifts the root down.

PassMax moved to endHeap part after re-heapifySorted part
192 (last position 12)86, 57, 48, 33, 42, 22, 26, 25, 12, 37, 1892
286 (last position 11)57, 42, 48, 33, 37, 22, 26, 25, 12, 1886, 92
357 (last position 10)48, 42, 26, 33, 37, 22, 18, 25, 1257, 86, 92
448 (last position 9)42, 37, 26, 33, 12, 22, 18, 2548, 57, 86, 92
542 (last position 8)37, 33, 26, 25, 12, 22, 1842, 48, 57, 86, 92
637 (last position 7)33, 25, 26, 18, 12, 2237, 42, 48, 57, 86, 92
733 (last position 6)26, 25, 22, 18, 1233, 37, 42, 48, 57, 86, 92
826 (last position 5)25, 18, 22, 1226, 33, 37, 42, 48, 57, 86, 92
925 (last position 4)22, 18, 1225, 26, 33, 37, 42, 48, 57, 86, 92
1022 (last position 3)18, 1222, 25, 26, 33, 37, 42, 48, 57, 86, 92
1118 (last position 2)1218, 22, 25, 26, 33, 37, 42, 48, 57, 86, 92
––(empty)12, 18, 22, 25, 26, 33, 37, 42, 48, 57, 86, 92

Sorted list: 12, 18, 22, 25, 26, 33, 37, 42, 48, 57, 86, 92

Complexity: building O(n), n − 1 sift-downs of O(log n) each, so O(n log n) overall.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Data Structure and Algorithm chapter 7 questions →