Heap Sort
Heap Sort
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
2. Next, we will learn how to turn a binary tree back into a heap
after it has been changed in a certain way.
12 14
8 14 8 12
Blue node does not Blue node has
have heap property heap property
10 8 8 5
1 2 3
10 10 12
8 5 12 5 10 5
12 8 8
OTHER CHILDREN ARE NOT AFFECTED
12 12 14
10 5 14 5 12 5
8 14 8 10 8 10
The node containing 8 is not affected because its parent gets larger, not
smaller.
The node containing 5 is not affected because its parent gets larger, not
smaller.
The node containing 8 is still not affected because, although its parent got
smaller, its parent is still greater than it was originally.
A SAMPLE HEAP
Here’s a sample binary tree after it has been heapified
25
22 17
19 22 14 15
18 14 21 3 9 11
22 17 22 17
19 22 14 15
19 22 14 15
18 14 21 3 9 11
18 14 21 3 9
11
22 17
19 22 14 15
18 14 21 3 9
11 17
19 22 14 15
18 14 21 3 9
22 17
19 11 14 15
18 14 21 3 9
22 17
19 21 14 15
18 14 11 3 9
22 17
19 22 14 15
18 14 21 3 9 11
0 1 2 3 4 5 6 7 8 9 10 11 12
25 22 17 19 22 14 15 18 14 21 3 9 11
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
The “root” is the first element in the array.
The “rightmost node at the deepest level” is the last element
Swap them...
0 1 2 3 4 5 6 7 8 9 10 11 12
25 22 17 19 22 14 15 18 14 21 3 9 11
0 1 2 3 4 5 6 7 8 9 10 11 12
11 22 17 19 22 14 15 18 14 21 3 9 25
0 1 2 3 4 5 6 7 8 9 10 11 12
22 22 17 19 21 14 15 18 14 11 3 9 25
0 1 2 3 4 5 6 7 8 9 10 11 12
9 22 17 19 22 14 15 18 14 21 3 22 25
Repeat until the last becomes first, and the array is sorted!
ANALYSIS I