Unit4 Heap
Unit4 Heap
4 Height of root = 3
1 3
Height of (2)= 1 2 16 9 10 Level of (10)= 2
14 8
3
USEFUL PROPERTIES
There are at most 2^l nodes at level l of binary tree
A Binary tree with depth (height) d has at most 2^ d+1-1 node
(Height of leaf node is 0)
height
4 Height of root = 3
1 3
Height of (2)= 1 2 16 9 10 Level of (10)= 2
14 8
4
THE HEAP DATA STRUCTURE
Def: A heap is a nearly complete binary tree with the
following two properties:
Structural property: all levels are full, except possibly the
last one, which is filled from left to right
Order (heap) property: for any node x
Parent(x) ≥ x
6
HEAP TYPES
Max-heaps (largest element at root), have the max-heap
property:
for all nodes i, excluding the root:
A[PARENT(i)] ≥ A[i]
8
OPERATIONS ON HEAPS
Maintain/Restore the max-heap property
MAX-HEAPIFY
9
MAINTAINING THE HEAP PROPERTY
Suppose a node is smaller than a child
Left and Right subtrees of i are max-heaps
To eliminate the violation:
Exchange with larger child
Move down the tree
Continue until node is not smaller than
children
10
EXAMPLE
MAX-HEAPIFY(A, 2, 10)
A[2] A[4]
A[2] violates the heap property A[4] violates the heap property
A[4] A[9]
14
Alg: BUILD-MAX-HEAP(A) 1
4
1. n = length[A]
2 3
3. do MAX-HEAPIFY(A, i, n) 8
2 9 10
16 9 10
14 8 7
A: 4 1 3 2 16 9 10 14 8 7
4 1 3 2 16 9 10 14 8 7
EXAMPLE: A
i=5 i=4 i=3
1 1 1
4 4 4
2 3 2 3 2 3
1 3 1 3 1 3
4 5 6 7 4 5 6 7 4 5 6 7
8
2 9 10
16 9 10 8 2 9 10
16 9 10 8 14 9 10
16 9 10
14 8 7 14 8 7 2 8 7
i=2 i=1
1 1 1
4 4 16
2 3 2 3 2 3
1 10 16 10 14 10
4 5 6 7 4 5 6 7 4 5 6 7
8
14 9 10
16 9 3 8
14 9 10
7 9 3 8
8 9 10
7 9 3
2 8 7 2 8 1 2 4 1
15
RUNNING TIME OF BUILD MAX HEAP
Alg: BUILD-MAX-HEAP(A)
1. n = length[A]
2. for i ← n/2 downto 1
O(n)
3. do MAX-HEAPIFY(A, i, n) O(lgn)
16
PROBLEMS
17
SOLUTION OF PROBLEM 1.
Min Heap 18
Max Heap
RESULT OF PROBLEM 2
result = [-2,1,5,9,4,6,7]
19
HEAPSORT
Goal:
Sort an array using heap representations
Idea:
Build a max-heap from the array
Swap the root (the maximum element) with the last element in the
array
“Discard” this last node by decreasing the heap size
Call MAX-HEAPIFY on the new root
Repeat this process until only one node remains
20
EXAMPLE: A=[7, 4, 3, 1, 2]
MAX-HEAPIFY(A, 1, 1)
21
ALG: HEAPSORT(A)
1. BUILD-MAX-HEAP(A)
2. for i ← length[A] downto 2
3. do exchange A[1] ↔A[i]
4. MAX-HEAPIFY(A, 1, i - 1)
22