Design & Analysis of Algorithms: DR Anwar Ghani
Design & Analysis of Algorithms: DR Anwar Ghani
Dr Anwar Ghani
• Heaps Operations
- Heap Fixing
- Heap Building
- Heap Sorting
Completeness Property: The completeness property implies that the tree has nodes at all
levels, except possibly at the lowest level. Further, at bottom level the nodes (leafs) are
organized in left to right positions. In other words, the nodes in the right positions at the
last level may be missing. A tree that contains nodes at all levels is called complete tree
Order Property: The order property implies that key in each node is larger than, or equal
to the keys in child nodes. This structure is referred to as max-heap . By contrast, in a min-
heap, each parental node contains a key which is smaller than or equal to the keys in the
child nodes. Thus, order property implies
key(parent) ≥ key(left ), key(parent) ≥ key (right) ( max-heap)
key(parent)≤ key(left ), key(parent) ≤ key (right) ( min-heap)
¾ Depending upon an application of heap, each node may contain other data items.
Such a heap is said to be a priority queue . The keys are usually, the priorities attached to
the data items. In scheduling application , for example, priorities are usually the order of
scheduling of different tasks.
Binary Heaps
Examples
The examples of max-heap and min-heap are shown in figures (a) and (b) below. Note that
each subtree in the heap is also a smaller heap of the same type.
25
22 15
8 16 12 10
3 7 11 9 6 5 1
12 10
18 21 15 14
25 40 29 26
57
2 3
40 35
4 5 6 7
18 21 25 14
8 9 10 11 12 13 14 15
2 4 19 17 22 15 10 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
57 40 35 18 21 25 14 2 4 19 17 22 15 10 3
(a) Array implementation
Binary Heap
Basic Operations
The basic operations on a heap data structure, implemented as an array, are:
HEAPIFY(A, i) - restores heap order property by fixing up an offending key, stored in a node
with index i
¾ The procedures PARENT, LEFT, and RIGHT require fixed amount of time to do the computations
on array indexes. Thus, running time for each of the above operations is θ(1)
Heap Fixing-Up
Algorithm
The heapify procedure is used to fix up a given node that violates the order property. It
consists of following steps:
Step #1: Compare the key of the offending node with the key of the left child
Select the index of the bigger key and store in the index variable largest
Step #2: Compare the key identified by index largest with the key in the right child
Step #3: Save index of the bigger key into the variable largest
Step #4: If the index of offending key is not equal to largest, then exchange key of the
parent node with the key identified by largest; else, exit
Step #5:Repeat Steps #1 through Step #4 , with the offending key identified by the
index largest
¾ In essence, offending key is trickled down until the heap order property is restored.
Heap Fixing-Up
Example
The heap fixing-up procedure is illustrated by the following example
(1) All keys in the tree structure satisfy Offending key 25
heap order property, except key 2, in the
leftmost position at level 1 (shaded red). 2 15
left child. 8 2 12 10
3 7 11 9 6 5 1
25
(3) All keys satisfy the max-heap order
property. It is also a complete tree The 16 15
3 7 2 9 6 5 1
Fixed up
Heapify Algorithm
Implementation
The heap is assumed to be implemented as an array. The index i of the offending key, heap size
n and array A are passed on to the procedure HEAFIFY( Ref: T.Cormen et al; with slight
modification . Comments have been added for elaboration of steps ). The key of offending node
is repeatedly compared with keys in child nodes, until heap order property is restored
7 96
56 17 87 73
76 32 96 31 76 75 17 54
38 24 87 75 2 15 73 54 38 24 32 65 2 15 31 7
(i) A binary tree with random keys (iii) Binary tree converted to a max-heap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
7 56 17 76 32 96 31 38 24 87 75 2 15 73 54 96 87 73 76 75 17 54 38 24 32 56 2 15 31 7
Step # 1: Select the key at parent of the last node in the tree
Step #2 : Heapify the tree using the key in the chosen node
Step #3: Choose the key in the next adjacent node on the left at the same level or the key
in the extreme right node at next higher level. Fix-up the heap using the selected key
.
Step #4: Repeat Step # 3, until the root is reached.
Start fixing up
25 12 9 11
Heap Building
Example
(4) The rightmost key 10, at next higher level 7
is considered. It is fixed up by exchanging
20 10
with the larger key 15 in the left child
25 16 15 14
18 12 9 11
18 12 9 11
7
(6) Finally, the key 7 in the root is fixed up. It
is exchanged with the larger key in the left 25 15
child. 20 16 10 14
18 12 9 11
Heap Building
Example
(7) The key 7 in new position violates the 25
order property. It is fixed up by exchanging
7 15
with the larger key 20 in the left child
20 16 10 14
18 12 9 11
18 12 9 11
25
(9) The binary tree is now converted into a
max heap. The tree is complete. Key in each 20 15
node is larger than the keys in the left child 18 16 10 14
and the right child
7 12 9 11
Heap Building Algorithm
Implementation
The heap building procedure works in top-up manner, starting with the parental node of
last right most child at the bottom level ( Ref: T.Cormen et al , with slight modification).
The pseudo code for heap building procedure is as follows.
Step #3: Covert the subtree, without the detached nodes, into heap by fixing-up key in the root
Step #4: Repeat Step#2 through Step #3 until the subtree reduces to a pair of nodes
¾ All detached keys and the last pair of keys in the subtree are now sorted in ascending order
Heap Sorting
Example
The heap sorting algorithm is is demonstrated by the following example.
1 2 3 4 5 6 7 8 9 10 11
(1) An unsorted sample array is show in index
7 20 10 18 11 15 14 25 12 9 16
figure (a). It is mapped into a complete key
binary tree depicted in figure (b). The (a) Sample unsorted array
numbers on top of the tree nodes are the 1 Array index
indexes of the array cells. Thus, the root 7
2 3
contains the first key 7 in the array, and the 20 10
last node at the bottom stores key 16 in cell 4 5 6 7
18 11 15 14
11 of the array 8 9 10 11
25 12 9 16
18 16 10 14
7 12 9 11
7 12 9 25
Building Heap
Example
(6) As a result of fixing up, the key 20 is 20
moved to the root, and key 11 to the bottom
18 15
level
12 16 10 14
7 11 9 25
12 16 10 14
7 11 9 25
9
(8) After the exchange, the last key is de-
linked from the heap. The subtree consists of 18 15
nine nodes 12 16 10 14
7 11 20 25
Building Heap
Example
(9) The key 9 in the root, violates the max
9
heap property.
18 15
12 16 10 14
7 11 20 25
12 16 10 14
7 11 20 25
12 9 10 14
7 11 20 25
Building Heap
Example
(12) The key 18 in the root is exchanged with
18
the last key 11 in the newly built tree
16 15
12 9 10 14
7 11 20 25
12 9 10 14
7 18 20 25
7 18 20 25
11 9 10 14
7 18 20 25
7
(17) After the exchange, the node containing
key 16 is detached from the tree. The tree 12 15
now consists of seven nodes. 11 9 10 14
16 18 20 25
Building Heap
Example
(18) After the exchange the key 7 is in the
7
root . The last key in the subtree is 14
12 15
11 9 10 14
16 18 20 25
16 18 20 25
11 9 10 7
16 18 20 25
Building Heap
Example
(21) The key 15 in the root is exchanged with 15
last key 7 in the heap
12 14
11 9 10 7
16 18 20 25
16 18 20 25
11 9 7 15
16 18 20 25
11 9 7 15
16 18 20 25
11 9 14 15
16 18 20 25
Building Heap
Example
(27) The key in the root violates heap order 7
property. It is fixed by exchanging with the
12 10
larger keys 12, 11 in the child nodes
11 9 14 15
16 18 20 25
7 9 14 15
16 18 20 25
7 9 14 15
16 18 20 25
Building Heap
Example
(30) After the exchange, the node with key 12 9
is detached from the subtree. The tree now
11 10
consists of four nodes
7 12 14 15
16 18 20 25
16 18 20 25
9 10
7 12 14 15
16 18 20 25
Building Heap
Example
(33) The key 11 in the root is exchanged with 11
the last key 7 in the heap 9 10
7 12 14 15
16 18 20 25
16 18 20 25
16 18 20 25
Building Heap
Example
(36) The max heap consists of three nodes, 10
with the largest key 10 in the root. 9 7
11 12 14 15
16 18 20 25
11 12 14 15
16 18 20 25
7 20 10 18 11 15 14 25 12 9 16
HEAPSORT( A)
1 BUILD-HEAP(A) ► Call BUILD-HEAP procedure to convert array into a heap
2 for j ← length[A] downto 2 ► Use bottom-up procedure
3 do exchange A[1] ↔ A[j] ► Exchange last key in the heap with the key in the root
4 heap-size ← heap-size – 1 ► Reduce the size of heap by one ( one key is discarded)
5 HEAPIFY(j, heap-size, A ) ► Fix up the key at root by calling HEAPIFY procedure
Visualization
Heap Sort Visualization
Analysis of Heap Operations
Analysis of Heap Fixing
Worst Case Scenario
An offending key is the key in some tree node that violates the heap order property. In worst case the
offending key appears at the root. In this situation the heap completeness property is not restored until the
key is moved to the bottom level. .
Offending key
At each level, the offending key is compared twice: First, the key in the parent node is
compared with the key in a left child node . Next, the larger of the keys is compared with the
key in the right child. If c is cost of one comparison, then total number of comparisons in worst
case would be 2ch, where h is the height of the heap. Thus, the worst running time T(h), in
terms of heap height, is given by
Tworst (h)= 2ch
Analysis of Heap Fixing
Worst Running Time
In order to express the running time in terms of number of nodes, we assume that the heap is
full. In other words, the last level contains maximum number of nodes, as shown in the figure
1=20
2=21
4=22
8=23
h
16=24
2h
2=21
4=22
8=23
h
16=24
2h-1
2h
In worst case of fixing-up the heap, all of the keys descend down to the bottom level . Further, at each
step the offending key is compared twice with the left and right children of parental node . Let c be the
unit cost of comparison. The table summarizes total cost of comparison of keys at each level
Level Number of Nodes Count of shifting down Total Cost
0 20 h 2c.h.20
1 21 h-1 2c.(h-1).21
2 22 h-2 2c.(h-2).22
-- -------- -------- --
i 2i h-i 2c.(h-i).2i
--- ------ ------ --
h-2 2h-2 2 2c.2.2h-2
h-1 2h-1 1 2c.1.2h-1
Analysis of Heap Building
Worst Running Time
The worst time Tbuild for building the heap is obtained by summing the last column :
Tbuild = 2ch.20 + 2c(h-1).21 + 2c(h-2).22+……..+ 2c.2.2h-2+ 2c.1.2h-1 ………(1)
As shown before, 2h+1 = n+1 and h
n= lg(n+1) -1, n being the heap size …………….(2)
Using summation notation
h −1
Tbuild = 2 c ∑ (h - i) 2i
i =0
h −1 h −1
h −1
= 2ch ∑ 2i - 2c ∑i =0
i 2i ………….. (3)
∑
i =0
2i = 2h -1 ( summing the geometric series )
i =0
h −1 m
∑
i =0
i2i = (h-2)2h + 2 ( summing aritho-geometric series ∑ i2i = (m-1) 2m+1 + 2 , ref math prelim )
i =1
Time to
build heap Time to fix-up heaps
of sizes n-1 to 2
It was shown previously that, in worst case, the BUILD-HEAP procedure takes θ(n) time.
Thus, Tbuild = θ(n)
Analysis of Heap Sorting
Running Time
The fixing-up procedure is applied repeatedly to sub-tree of sizes n-1, n-2, …4,3
From analysis of heap fixing it follows that running time to fix a heap of size n is given by
Tfix (n) = 2c( lg(n+1) -1) ), ……………..(1)
where c cost of comparing keys
In heap sorting algorithm, the fixing-up procedure is applied repeatedly to subtrees of sizes
n-1, n-2…,3 . Using result of equation (1),
Tfix(n) = 2c [ (lg(n) -1)+ (lg(n-1)-1) +…+ (lg(4)-1) ]
= 2c[ lg ((n).(n-1) …..4 ) - ( n-2) ]
= 2c[ lg (n)! – n –lg(6) +2]
=2c[ lg (n!) – n –lg(6) + 2]
=2c [ lg( √(2πn) (n/e)n ) –n - lg(6) + 2] (Using Stirling’s approximation for n!)
= c[ lg(n) + 2nlg(n) - 2 n lg(e) - 2n ] + k , where k is sum of constant terms
Now Lim Tfix(n) / nlg(n) = [ c( lg(n)+2nlg(n) - 2 n lg(e) -2n ) + k ] / n lg(n)
n→∞
= 2c ( constant)
Therefore, Tfix(n) = θ( n lg(n) )
Tsort(n) = Tbuild(n) + Tfix(n)
= θ(n) +θ(n lg n )
= θ(n lg n) ( ignoring lower order term n)