5._Heap_Sort.ppt
5._Heap_Sort.ppt
Recall:
⚫ The depth of a node is its distance from the
root.
⚫ The depth of a tree is the depth of the
deepest node.
A binary tree of depth n is balanced if all the
nodes at depths 0 through n-2 have two
children.
n-2
n-1
n
Balanced Balanced Not balanced
LEFT-JUSTIFIED BINARY TREES
1 1 1
0 0 2
1 1
8 5 5 5
2 0
1
8 8
2
OTHER CHILDREN ARE NOT
AFFECTED
1 1 1
2 2 4
1 1 1
5 5 5
0 4 2
1 1 1
8 8 8
4 0 0
1 2 1 1
9 2 4 5
1 1 2 1
3 9
8 4 1 1
1 2 1 1
9 2 4 5 1 2 1 1
9 2 4 5
1 1 2 1
3 9
8 4 1 1 1 1 2
3 9
8 4 1
Remove the rightmost leaf at the deepest
level and use it for the new root
THE HEAPIFY METHOD I
Our tree is balanced and left-justified, but no
longer a heap
However, only the root lacks
1
the heap property
1
2 1
2 7
1 2 1 1
9 2 4 5
1 1 2
3 9
8 4 1
1 2 1 1
9 2 4 5
1 1 2
3 9
8 4 1
1 1 1 1
9 1 4 5
1 1 2
3 9
8 4 1
1 2 1 1
9 1 4 5
1 1 1
3 9
8 4 1
1 2 1 1
9 2 4 5
1 1 2 1
3 9
8 4 1 1
0 1 2 3 4 5 6 7 8 9 10 11 12
2 2 1 1 2 1 1 1 1 2 1
3 9
5 2 7 9 2 4 5 8 4 1 1
Notice:
⚫ The left child of index i is at index 2*i+1
⚫ The right child of index i is at index 2*i+2
⚫ Example: the children of node 19 ( index 3) are
18 (index 7) and 14 (index 8)
REMOVING AND REPLACING THE
ROOT
0 1 2 3 4 5 6 7 8 9 10 11 12
1 2 1 1 2 1 1 1 1 2 2
3 9
1 2 7 9 2 4 5 8 4 1 5
0 1 2 3 4 5 6 7 8 9 10 11 12
2 2 1 1 2 1 1 1 1 1 2
3 9
2 2 7 9 1 4 5 8 4 1 5
0 1 2 3 4 5 6 7 8 9 10 11 12
2 1 1 2 1 1 1 1 2 2 2
9 3
2 7 9 2 4 5 8 4 1 2 5
...And again, remove and replace the root node
Remember, though, that the “last” array index
is changed
Repeat until the last becomes first, and the
ANALYSIS I