Lect 15
Lect 15
Content
• Introduction to Heap
• Representation of Heap
3 4
• Max heap
• For every node in the heap, the value stored in that node is greater than
or equal to the value in each of its children
• Min heap
• For every node in the heap, the value stored in that node is less than or
equal to the value in each of its children
5 6
1
1/4/2023
7 8
9 10
• reheapifyDownward:
• It involves moving the element down from the root position until
either it ends up in a position where order property is satisfied or it
hits the leaf node.
(c) (d)
11 12
2
1/4/2023
13 14
15 16
17 18
Heapify(a,n)
1. Set index=Parent of node with index n
2. Repeat step 3 For i=index to 1 in setp of -1
3. Call reheapifyDownward(a,i) (see slide # 8)
4. Endif
5. Return
3
1/4/2023
19 20
Heapify(a,n)
1. Set index=Parent of node with index n
2. Repeat step 3 For i=index to 1 in setp of -1
3. Call reheapifyDownward(a,i) (see slide # 8)
4. Endif
5. Return
Equivalent Binary Tree
21 22
Unsorted Array
1 2 3 4 5 6 7 Unsorted Array
1 2 3 4 5 6 7
10 70 15 70 10 5 12 35 50
70 15 10 50 5 12 35 50 10
23 24
Heap Sort
1 2 3 4 5 6 7 1 2 3 4 5 6 7
70 15 50 5 12 35 10 50 15 10 5 12 35 70
Heapify(a,n)
1. Set index=Parent of node with index n
2. Repeat step 3 For i=index to 1 in setp of -1
3. Call reheapifyDownwardward(a,i) (see slide # 8)
4. Endif
5. Return
4
1/4/2023
25 26
Unsorted Sorted
1 2 3 4 5 6 7
50 15 35 5 12 10 70
27 28
Unsorted Sorted
1 2 3 4 5 6 7
35 15 10 5 12 50 70
29 30
Unsorted Sorted
1 2 3 4 5 6 7
15 12 10 5 35 50 70
5
1/4/2023
31 32
Unsorted Sorted
1 2 3 4 5 6 7 Unsorted Sorted
12 5 10 15 35 50 70 1 2 3 4 5 6 7
10 5 12 15 35 50 70
33 34
35
Thank You