void Heapify(T* sortee, int currentRootIndex,
int size)
{
int finish = 0, maxChildIndex = 0;
while(currentRootIndex * 2 <= size && !finish) { if (currentRootIndex * 2 == size) { maxChildIndex = currentRootIndex * 2; } // To check next leaf with next+1 leaf else if (*(sortee + currentRootIndex * 2) > *(sortee + currentRootIndex *2 + 1))
{
maxChildIndex = currentRootIndex * 2;
}
else
{
maxChildIndex = currentRootIndex *2 + 1;
}
if (*(sortee + maxChildIndex)
> *(sortee + currentRootIndex))
{
int temp = *(sortee + maxChildIndex);
*(sortee + maxChildIndex) = *(sortee + currentRootIndex);
*(sortee + currentRootIndex) = temp;
currentRootIndex = maxChildIndex;
}
else
{
finish = 1;
}
}
}
// ================================================
template
void BuildHeap(T* sortee, int currentRootIndex,
int size)
{
for (int loop = (size / 2) - 1; loop>=0; --loop)
{
Heapify(sortee, loop, size);
}
}
// ================================================
template
void HeapSort(T* sortee, int size)
{
for (int loop = (size / 2) - 1; loop>=0; --loop)
{
BuildHeap(sortee, loop, size);
}
// To swap largest with last
for (int loop = size - 1; loop >= 1; --loop)
{
int temp = *(sortee + 0);
*(sortee + 0) = *(sortee + loop);
*(sortee + loop) = temp;
Heapify(sortee, 0, loop-1);
}
}
No comments:
Post a Comment