Professional Documents
Culture Documents
DS 9
DS 9
DS 9
4 9 3
4 8 7
9 9
4 9 8
4 2 7
3 1
4 3
6 7 9 3
8 6
Complete binary tree with 9 nodes
that is also a min tree.
Max Heap With 9 Nodes
8 7
6 7 2 6
5 1
Complete binary tree with 9 nodes
that is also a max tree.
A Heap Is Efficiently Represented As An
Array
8 7
6 7 2 6
5 1
9 8 7 6 7 2 6 5 1
0 1 2 3 4 5 6 7 8 9
Moving Up And Down A Heap
1
9
2 3
8 7
4 5 6 7
6 7 2 6
5 1
8 9
Inserting An Element Into A Max Heap
8 7
6 7 2 6
5 1 7
8 7
6 7 2 6
5 1 5
7
New element is 5.
Inserting An Element Into A Max Heap
8 7
6 7 2 6
5 1 7
8 7
6 2 6
5 1 7
6 8 2 6
5 1 7
20
9 7
6 8 2 6
5 1 7
20
9 7
6 8 2 6
5 1 7
20
9 7
6 8 2 6
5 1 7
20
9 7
6 2 6
5 1 7 8
20
15 7
6 9 2 6
5 1 7 8
15 7
6 9 2 6
21
Deletion from a Max Heap
20
15 7
15 7
6 9 2 6
5 1 7 8
6 9 2 6
22
Deletion from a Max Heap
20
15 7
15 7
6 9 2 6
5 1 7 8
6 9 2 6
23
Deletion from a Max Heap
8 20
15 7
15 7
6 9 2 6
5 1 7 8
6 9 2 6
24
Deletion from a Max Heap
15 20
15 7
8 7
6 9 2 6
5 1 7 8
6 9 2 6
25
Deletion from a Max Heap
15 20
15 7
9 7
6 9 2 6
5 1 7 8
6 8 2 6
26
Max Heap Initialization
• Heap initialization means to construct a heap by
adjusting the tree if necessary
• Example: input array = [1,2,3,4,5,6,7,8,9,10,11]
27
Max Heap Initialization
- Start at rightmost array position that has a child.
28
Max Heap Initialization
29
Max Heap Initialization
30
Max Heap Initialization
31
Max Heap Initialization
32
Max Heap Initialization
•Are we finished?
•Done!
33
Exercise
convert the following complete binary tree into max tree
34
Exercise
• The heapified tree
35
Exercise
insert 15 in to the heap
36
Exercise
• now insert 20 into the heap
37
Applications of Heaps
• Sort (heap sort)
• Machine scheduling
• Huffman codes
38