#include <iostream>

using namespace std;


//自上而下调整成小顶堆
//nArray[iFrom+1,.....,iTo]是一个小顶堆
void AdjustHeapFromTopToDown( int nArray[], int iFrom, int iTo )
{
if ( iFrom < 0 || iTo < 0 || iFrom >= iTo )
{
return;
}

//数组索引从0开始,左孩子2(i+1)-1,右孩子2(i+1)
int nTemp = nArray[iFrom];
int i = 2*(iFrom+1) - 1;
while( i <= iTo )//存在左孩子
{
if ( ( (i+1) <= iTo ) && nArray[i+1] < nArray[i] )
{
i = i + 1;//右孩子更小
}

if ( nArray[i] < nTemp )
{
nArray[(i-1)/2] = nArray[i];

i = 2*(i+1) - 1;
}
else
{
break;
}
}

nArray[(i-1)/2] = nTemp;

}

void HeapSort( int nArray[], int nCount )
{
if ( nCount <= 0 )
{
return;
}

//将数组调整成一个小顶堆
for( int i = ( nCount - 2 ) / 2; i >= 0; --i )
{
AdjustHeapFromTopToDown( nArray, i, nCount - 1 );
}

//排序
for ( int i = 0; i < nCount; ++i )
{
cout << nArray[0] << " ";

//将堆中最后一个元素赋给堆的根结点,重新自上而下调整
nArray[0] = nArray[nCount-1-i];
AdjustHeapFromTopToDown( nArray, 0, nCount-1-i );
}
cout << endl;
}


int main()
{
int nArray[] = { 6, 7, 3, 5, 4, 9, 0, 0, 11, 23, 3, 2, 1, 12, 13, 14, 15, 16, 17, 1, 2, 3,
4, 4, 5, 6, 7, 9, 8, 7, 6, 5, 4, 89, 78, 90 };
HeapSort( nArray, _countof(nArray) );


return 0;
}



作者:山丘儿