Ada Module3.Pptx
Ada Module3.Pptx
4 5 6
2 4 1
Nearly complete binary tree
• Every level except bottom is complete.
• On the bottom, nodes are placed as left as possible.
1 1
6 6
2 2 3
3 5 3
5 3
4 5 6 4 5 6
2 2 4 1
1 4
No! Yes!
Heap
• Definition: A heap can be defined as a binary tree
with keys assigned to its nodes, one key per
node, provided the following two conditions are
met:
Hea
p?
Properties of Heap
1. There exists exactly one essentially complete
binary tree with n nodes. Its height is equal to
2. The root of a heap always contains its
largest element.
3. A node of a heap considered with all its
descendants is also a heap.
Properties of Heap
4. A heap can be implemented as an array by
recording its elements in the top down,
left-to-right fashion.
1 1
6 6
2 2 3
3 5 3
5 3
4 5 6 4 5 6
2 2 4 1
1 4
No! Yes!
Construction of Heap
• There are two principal alternatives for
constructing Heap.
1. Bottom-up heap construction
2. Top-down heap construction
Example from textbook
Building a Max-Heap
1 3
1 1
2 9
6 0
14 8 7
1
6
1 1
4 0
7 9 3
8
2 4 1
• Sort the given list of numbers using heap sort:
2, 9, 7, 6, 5, 8. (08 Marks)
Illustration -2
Inserting a new key (10)
Illustration
2, 5, 6, 7, 8, 9
Heapsort - Analysis of
efficiency
• Stage-1: heap construction - O(n)
• Stage-2: For the number of key comparisons,
C(n), needed for eliminating the root keys from
the heaps of diminishing sizes from n to 2, we
get the following inequality: