Leaf nodes are already heaps(그 자체로 이미 HEAP)
Move up a level in tree and continue reheaping until we reach the root node
code로 구현한 것
#ifndef HEAPSORT_H
#define HEAPSORT_H
template<class ItemType>
void ReheapDown(ItemType elements[], int root, int bottom);
template<class ItemType>
void HeapSort(ItemType values[], int numValues);
template<class ItemType>
void ReheapDown(ItemType elements[], int root, int bottom)
// Post: Heap property is restored.
{
int maxChild;
int rightChild;
int leftChild;
leftChild = root * 2 + 1;
rightChild = root * 2 + 2;
if (leftChild <= bottom)
{
if (leftChild == bottom)
maxChild = leftChild;
else
{
if (elements[leftChild] <= elements[rightChild])
maxChild = rightChild;
else
maxChild = leftChild;
}
if (elements[root] < elements[maxChild])
{
Swap(elements[root], elements[maxChild]);
ReheapDown(elements, maxChild, bottom);
}
}
}
template<class ItemType>
void HeapSort(ItemType values[], int numValues)
// Pre: Struct HeapType is available.
// Post: The elements in the array values are sorted by key.
{
int index;
// Convert the array of values into a heap.
//자식을 가지고 있는 (leaf가 아닌) 부모들부터 ReheapDown을 진행 - leaf는 이미 그 자체가 heap이므로
//numValues / 2 - 1부터 0까지는 부모들의 인덱스임
for (index = numValues / 2 - 1; index >= 0; index--)
ReheapDown(values, index, numValues - 1);
//즉 각 subtree마다!!! ReheapDown을 해주는 것(각 부모를 루트로 서브트리임)
// Sort the array. 이 과정은 걍 굳이..? 그냥 따로 배열 하나 만들어서
//루트들 빼서 저장하는 게 더 낫다고 교수님께서 말씀하심
for (index = numValues - 1; index >= 1; index--)
{
Swap(values[0], values[index]);
ReheapDown(values, 0, index - 1);
}
}
#endif