Professional Documents
Culture Documents
1. Heap
2. Heap Types
3. Heap as an Array
4. Array Representation of Max Heaps
5. Operations on Heap
Heap
7
It doesn‘t matter that 4 in
4
level 1 is smaller than 5 in
5 2
level 2
Heap (top to bottom and left to right)
Heap Example
10 10 10
5 7 5 7 5 7
4 2 1 2 1 6 2 1
Note: Heap’s elements are ordered top down (along any path down
from its root), but they are not ordered from left to right
Heap Types
PARENT ≥ child
Min-heaps (smallest element at root), have the min-heap
property:
PARENT ≤ child
Heap Types (Example)
7 1
5 5 2 5
4 2 4 3 4 5 6 7
Max-heaps Min-heaps
Heap as an array
(i-1)/2 i
Array Representation of Max Heaps
Heapsize[A] ≤ length[A] 2 4 1
Array Representation of Max Heaps
0
The elements in A[n/2]…..A[n-1]
16 are leaves
i.e. A[5] to A[9]
1 2
Parents are A[0]………..A[n/2-1]
14 10
i.e. A[0] to A[4]
3 4 5 6
8 7 9 3 The root have the maximum element of
7 8 9
the heap
2 4 1 i.e. A[0]=16
Operations on Heaps
Maintaining the Heap Property
Maintaining the Heap Property
When:
Left and Right subtrees of i are
max-heaps and
A[i] breaks the heap
property.
A[i] may be smaller than its
children
MAX-HEAPIFY(A, i, n)
1. LEFT_child = 2i+1
2. RIGHT_child =2i+2
3. If LEFT_child < n and A[LEFT_child] > A[i]
4. then largest_index = LEFT_child
5. else largest_index = i
6. If RIGHT_child < n and A[RIGHT_child] > A[largest_index]
7. then largest_index = RIGHT_child
8. if largest_index ≠i
9. then exchange A[i] ↔ A[largest_index]
10. MAX-HEAPIFY(A, largest_index, n)
Initializing A Max Heap
14 7
2 8 1
14
4 7
2 8 1
14
8 7
2 4 1
Done
Building a Heap
when, 4
Alg: BUILD-MAX-HEAP(A)
0
1. n = length of A[] 4
14 8 7
A: 4 1 3 2 16 9 10 14 8 7
Building A Max Heap
1
2 3
4 5 6 7
8 9 7
10 11
8
2 3
4 5 6 7
8 9 7
10 11
8
2 3
4 11 6 7
8 9 7
10 85
2 3
4 11 6 7
8 9 7
10 85
2 3
9 11 6 7
8 4 7
10 85
2 3
9 11 6 7
8 4 7
10 85
2 7
9 11 6 3
8 4 7
10 85
2 7
9 11 6 3
8 4 7
10 85
11 7
9 2 6 3
8 4 7
10 85
11 7
9 10 6 3
8 4 28 75
11 7
9 10 6 3
8 4 72 8
5
11
1 7
9 10 6 3
8 4 72 8
5
11
10 7
9 1 6 3
8 4 72 8
5
11
10 7
9 5 6 3
8 4 72 18
Done
Exercise
Input Array 5 4 9 7 19 8 17 2 6 5 21
Output Array/
21 19 17 7 5 8 9 2 6 5 4
Heap Array
Exercise
1 2
4 9
3 4 5 6
7
7 8 9
19 8 17
2 6 5 21
Books
1. https://en.wikipedia.org/wiki/Data_structure