题目:基于数组的堆排序
思路:主要分为两步
(1)对无序数组调整成大根堆(从小到大的排序)
<1> 对非叶子结点进行调整
<2> 从最后一个非叶子结点开始,一直到根结束
<3> 每次调整,都调整一条路径,从待调整元素的位置开始,一直到叶子结点为止。
(2)把堆顶与待排序的最后一个元素交换,之后调整堆
代码:
void Swap(int& nFirst,int& nSec)
{
int nTmp = nFirst;
nFirst = nSec;
nSec = nTmp;
}
/*调整堆:由上往下调整,每次调整都处理一条路径*/
void HeapAdjust(int nArr[],int nLen,int nHole)
{
int nKey = nArr[nHole];
for (int nChild = 2 * nHole;nChild <= nLen;nChild *= 2)
{
//找最大的孩子
if (nChild < nLen && nArr[nChild + 1] > nArr[nChild])
{
nChild++;
}
//最大孩子与父亲比较
if (nArr[nChild] < nKey)
{
break;
}
nArr[nHole] = nArr[nChild];
nHole = nChild;//下一次调整nHole
}
nArr[nHole] = nKey;
}
/*对待排序元素,先调整成大根堆,后排序*/
void HeapSort(int nArr[],int nLen)
{
//调整
for (int i = nLen / 2;i >= 1;i--)
{
HeapAdjust(nArr,nLen,i);
}
//排序
for (int i = nLen;i > 1;i--)
{
Swap(nArr[i],nArr[1]);
HeapAdjust(nArr,i - 1,1);
}
}