J.E.D.I
Figure 1.51 Two Representations of the elements a l g o r i t h m s
4.7.1 Sift-Up
A complete binary tree may be converted into a heap by applying a process called sift- up. In the process, larger keys “sift-up” the tree to make it satisfy the heap-order
property. This is a bottom-up, right-to-left, process in which the smallest subtrees of a complete binary tree are converted into heaps, then the subtrees which contain them,
and so on, until the entire binary tree is converted into a heap.
Note that when the subtree rooted at any node, say α
, is converted into a heap, its left and right subtrees are already heaps. We call such a subtree an almost-heap. When an
almost heap is converted into a heap, one of its subtrees may cease to be a heap i.e., it may become an almost heap. This, however, may be converted to a heap and the
process continues as smaller and yet smaller subtrees lose and regain the heap property, with LARGER keys migrating upwards.
4.7.2 Sequential Representation of a Complete Binary Tree
Data Structures 62
J.E.D.I
A complete binary tree may be represented sequentially in a one-dimensional vector of size n in level-order. If the nodes of a binary tree are numbered as illustrated below,
Figure 1.52 A complete Binary Tree then it can be represented sequentially in a vector named KEY, as follows:
Figure 1.53 Sequential Representation of a Complete Binary Tree Sequential representation of a complete binary tree enables locating the children if
any, the parent if it exists and the parent of a node in constant time by using the following formula:
• if 2i ≤
n, the left son of node i is 2i; otherwise, node i has no left son • if 2i + 1
≤ n, the right son of node i is 2i + 1; otherwise, node i has no right
son • if 1 i
≤ n, the father of node i is
i2
The following method implements the sift up process on sequentially represented
complete binary tree: Converts an almost-heap on n nodes rooted at i into a heap
private void siftUp int i, int n {
int k = key[i]; keep key at root of almost-heap int child = 2 i; left child
while child = n { if the right child is bigger, make the child point
to the right child if child n key[child+1] key[child] child++ ;
if heap property is not satisfied if key[child] k{
key[i] = key[child] ; Move the child up
Data Structures 63
J.E.D.I
i = child ; child = 2 i; Consider the left child again
} else break;
} key[i] = k ; this is where the root belongs
} To convert a binary tree into an almost-heap:
Convert key into almost-heap for int i=n2; i1; i--{
first node that has children is n2 siftUpi, n;
}
4.7.3 The Heapsort Algorithm