To make the implementation of the heap more robust, people usually call the two operations which you can make to a node: sift
and percolate
sift
is bringing the node as much down as possible on the tree by switching the node with the best of the two sons you find.
there is a possible implementation of the sift
procedure
public void sift (int i)
{
while (i != 0)
{
if (compare(heapData[i], parentValue(i)))
{
switchValuesAtIndexes(parentIndex(i), i);
i = parentIndex(i);
}
else
break;
}
}
percolate
is bringing the node as much up as possible on the tree by switching the node with the parent.
public void percolate (int i)
{
while (true)
{
if (indexExists(leftIndex(i)) && (!indexExists(rightIndex(i)) && compare(leftValue(i), heapData[i]) || indexExists(rightIndex(i)) && compare(leftValue(i), rightValue(i)) && compare (leftValue (i), heapData[i])))
{
switchValuesAtIndexes(leftIndex(i), i);
i = leftIndex(i);
}
else
if (indexExists(rightIndex(i)) && (compare (rightValue(i), leftValue(i)) && compare (rightValue(i), heapData[i])))
{
switchValuesAtIndexes(rightIndex(i), i);
i = rightIndex(i);
}
else
break;
}
}
To build the heap, you will need to apply sift
or percolate
(or both) to each element of the array
To sort the heap you constructed you will have to print the first element (which is the best of all heap accorting to a comparer which you define, min, max, etc)
Then you will have to "overwrite" the first element with the last and delete the last and then you'll have to apply sift
on the first element to bring it to it's right position in the heap. And you repeat until there's no element left in the heap