584 Programming and Data Structures
OUTPUT;
Enter a Number ( 0 to stop: 13 4 2 9 0
Tree in preorder sequence: 1 3 2 4 9
Heap Sort
In heap sort, we use the binary tree in which the nodes are arranged in specific prearranged order.
The rule prescribes that each node should have bigger value than its child node. The following
steps are to be followed in heap sort.
1) Arrange the nodes in the binary tree form.
2) Node should be arranged as per specific rules.
3) If the inserted node is bigger than its parent node then replace the node.
4) If the inserted node is lesser than its parent node then do not change the position.
5) Do not allow entering nodes on right side until the child nodes of the left are fulfilled.
6) Do not allow entering nodes on left side until the child nodes of the right are fulfilled.
7) The procedure from step 3 to step 6 is repeated for each entry of the node.
Consider the numbers 56, 23, 10, 99, 6, 19, 45, 45, 23 for sorting using heap. Sorting process is
illustrated in Fig. 16.7.
1) At first, we pick up the first element 56 from the list. Make it as the root node.
2) Next, take the second element 23 from the list. Insert this to the left of the root node 56. Refer to
Fig. 16.7 (2).
3) Then take the third element 10 from the list for insertion. Insert it to the right of the root node.
4
) Take the fourth element 99. Insert it to the left side of node 23. The inserted element is greater
than the parent element hence swap 99 with 23. But the parent node 56 is smaller than the child
node 99 hence 99 and 56 are swapped. After swapping 99 becomes the root node. This is shown
in Fig. 16.7 (4) and (5).
5) Consider the next element 6 to insert in the tree. Insert it at the left side . There exists a left node
hence insert it to the right of 56. Refer to Fig. 16.7 (6).
6) Element 19 is inserted to the right side of 99 because the left side gets full. Insert the element 19
to the right side of node 10. However, the parent element is lesser than the child hence swap 19
with 10.
7) Now element 45 is to be inserted at the right side of 19. However, the parent element is having
value lesser than the child element hence swap 45 with 19. Refer to Fig. 16.7 (9) and (10).
8) Now the right side is fully filled hence add the next element 45 to the left. The element 45 is
inserted at the last node of left i.e., 23. However, the parent element is having value lesser than
the child element hence swap 45 with 23. Refer to Fig. 16.7 (11) and (12).
9) Insert the last element 23 to the left side node i.e. 45. The left of 45 is already filled hence insert
element 23 at the right of 45. Refer to Fig. 16.7 (13).
10) At last, we get a sorted heap tree, as shown in Fig. 16.7 (13).