Reputation: 69
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
G D A N S K S O P O T 1 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 G D A N S K S O P O T T O S P O N S K A T P S O D T S S P O G D answer in total. t s s p o k a o n g d
I do understand the first 3 lines, but the rest I fail to understand. Does anyone have the time to explain :)
Upvotes: 2
Views: 923
Reputation: 351308
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
/ \ → / \
O T O S*
In the subtree rooted at 4, the letter N sifts down to the right:
N* P
/ \ → / \
O P O N*
In the subtree rooted at 3, the letter A sifts down to the right:
A* S
/ \ → / \
K S K A*
In the subtree rooted at 2, the letter D sifts down to the right twice:
D* T T
/ \ / \ / \
P T → P D* → P S
/ \ / \ / \ / \ / \ / \
O N O S O N O S O N O D*
In the subtree rooted at 1, the letter G sifts down three times:
G* T T T
/ \ / \ / \ / \
/ \ / \ / \ / \
T S → G* S → S S → S S
/ \ / \ / \ / \ / \ / \ / \ / \
P S K A P S K A P G* K A P O K A
/ \ / \ / \ / \ / \ / \ / \ / \
O N O D O N O D O N O D O N G* 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.
Upvotes: 4