Lab Program 4 Heapsort
Lab Program 4 Heapsort
HEAP SORT
HEAPS and HEAPSORT
• A heap is a binary tree with keys assigned to its nodes (one key
per node) provided the following two conditions are met:
1. The binary tree is essentially complex. i.e., all its levels are full except
possibly the last level where only the rightmost leaves may be missing.
2. The key at each node is greater than or equal to the keys at its children.
HEAP
HEAP
• Max heap (Descending Heap) is almost complete
binary tree such that an item at any given node >= (left
child and right child).
• Min heap (Ascending Heap) is almost complete
binary tree such that an item at any given node <= (left
child and right child). 32
Max Heap Min Heap
because because
parent 67 72 parent
>=child <=child
76 85 89
PROPERTIES OF MAX HEAP
• There exists exactly one essential complete binary tree with ‘n’
nodes . Its height = log2n.
• Root of a heap always contains its largest element
• A node of a heap considered with all its descendants is also a
heap.
• A heap can be implemented in an array H by recording its
elements in(p)the top-down,
0 left-to-right
1 2 fashion
3 4 leaving
5 H[0]
6
1
unused. 72 72 67 45 34 42 40
(2p (2p+
2) 3 1)
67 45 Parents Leaves
4
34 42 40
5 6
BOTTOM-UP HEAP CREATION
• It initializes the essentially complete binary tree with n nodes by placing keys in
the order given and then “heapifies” the tree as follows.
• Starting with the last parental node, the algorithm checks whether the parental
dominance holds for the key in this node.
• If it does not, the algorithm exchanges the node’s key K with the larger key of its
children and checks whether the parental dominance holds for K in its new
position.
• This process continues until the parental dominance for K is satisfied.
• After completing the “heapification” of the subtree rooted at the current parental
node, the algorithm proceeds to do the same for the node’s immediate predecessor.
The algorithm stops after this is done for the root of the tree.
Bottom-Up Heap Algorithm
31 21 42 14 16 12
(Already a max
heap so exchange
root 100 with leaf
45)
(Sorted array)
SAMPLE INPUT AND OUTPUT OF HEAPSORT