Heap sort begins by building a heap of the data. A heap can be visualized as a binary tree where each parent node is greater than its successors. In practice, the heap can easily be represented by a simple array where the left and right children of the ith node in the array will be at positions 2*i+1 and 2*i+2 respectively. For example, the following is a heap:
This heap above can be represented using an array as follows:
1. Each node is greater than its successors (for sorting in ascending order).
2. By virtue of (1), the largest node will always be on top of the heap.
Now that we know what the heap is, let’s see how we can generate such a heap out of unsorted data.
Building the Heap.
Before we talk about building a heap, we must first discuss a sifting procedure. The sifting procedure basically sifts a given node downward through the tree until it reaches its rightful place in the tree. I may keep using the term ‘node’ simply because its easier to visualize things that way but remember that in practice, a node is nothing but an element in a list. The sifting algorithm is pretty straight-forward.
Procedure SIFT(int siftNode, int heapSize)
1. Start with the position of the node to be sifted.
2. If either of the sift node’s children are larger than it, then swap the sift node with the larger of its children.
3. If neither of the sift node’s children are larger than it or the end of the heap has been reached then exit.
4. Otherwise, go to step 2.
Procedure Heapify()
1. siftNode = inputDataList.length()-1
2. while siftNode >= 0
{
3. Invoke SIFT( siftNode, inputDataList.length() )
4. siftNode = siftNode – 1
}
Sometimes, building an initial heap out of the input data is known as “Heapifying” the data. We are not done yet. The heap has to now be sorted and we'll see how that can be done soon. Until then, have a nice week!
No comments:
Post a Comment