#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
void HeapAdjust(int* pHeap, int i, int length)
{
int child;
for (; 2*i + 1 < length; i = child)
{
child = i*2 + 1;
int rightChild = child + 1;
if (rightChild < length && pHeap[rightChild]>pHeap[child]) child = rightChild;
if (pHeap[child] > pHeap[i])
{
int temp;
temp = pHeap[child];
pHeap[child] = pHeap[i];
pHeap[i] = temp;
}
else
{
break;
}
}
}
void HeapSort(int* pHeap, int length)
{
for (int i = length/2 - 1; i >= 0; i--)
{
HeapAdjust(pHeap, i, length);
}
for (int i = length - 1; i > 0; i--)
{
int temp;
temp = pHeap[0];
pHeap[0] = pHeap[i];
pHeap[i] = temp;
HeapAdjust(pHeap, 0, i);
}
}
int main()
{
int nArray[10];
copy(istream_iterator<int>(std::cin), istream_iterator<int>(), nArray);
HeapSort(nArray, 10);
copy(nArray, nArray + 10, ostream_iterator<int>(std::cout, " "));
system("pause");
}<span style="white-space:pre"> </span>
注意:1.这里数组的索引是零开头的,所以最后一个非叶子节点是length/2 - 1
2.数组的索引是零开头的,节点i的左子树是2*i+1,右子树是2*i+2