简体   繁体   中英

Heap sort (bottom up)

I'm trying to do one exam that I have, and simply cannot understand the method. This is heap sort Bottom up heap construction

This is my task

GDANSKSOPOT\n1 2 3 4 5 6 7 8 9 10 11 

The solution is (I do understand the 2nd line)

Bottom Up Heap-construction:

 1 2 3 4 5 6 7 8 9 10 11 GDANSKSOPOT TOS PON SKA TPSOD TSSPOGD answer in total. tsspokaongd

I do understand the first 3 lines, but the rest I fail to understand. Does anyone have the time to explain :)

We have this tree

             G
           /   \
          /     \             
        D        A  
      /  \      / \
    N      S   K   S  
   / \    / \
  O   P  O   T

...represented as:

1  2  3  4  5  6  7  8  9 10 11
G  D  A  N  S  K  S  O  P  O  T

The Heap-construction algorithm will heapify subtrees rooted at position 5, then at 4, 3, 2, and finally 1. Each of the lines in the solution lists letters of the nodes that are involved in the corresponding heapify operation:

  • In the subtree rooted at 5, the letter S sifts down to the right:

     S* T / \\ → / \\ OTOS*
  • In the subtree rooted at 4, the letter N sifts down to the right:

     N* P / \\ → / \\ OPON*
  • In the subtree rooted at 3, the letter A sifts down to the right:

     A* S / \\ → / \\ KSKA*
  • In the subtree rooted at 2, the letter D sifts down to the right twice:

     D* TT / \\ / \\ / \\ PT → PD* → PS / \\ / \\ / \\ / \\ / \\ / \\ ONOSONOSONOD*
  • In the subtree rooted at 1, the letter G sifts down three times:

     G* TTT / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ TS → G* S → SS → SS / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ PSKAPSKAPG* KAPOKA / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ ONODONODONODONG* D

Each of the above root-sift-downs correspond to one line in the solution you quote. Such a line lists the nodes that are somehow involved in the sifting down operation, because their value is being compared in the process. So, for example, in this last step, G is compared with both T and S, then G sifts down to the left, and is compared with P and S. G sifts down further and is compared with O and D to finally find its place as a leaf. This is why that final line has those letters, and it lists them as where they are after the transformation has completed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM