先从最后一个非终端节点开始调整,接着调整前一个节点,一直到顶,初始构建堆。
然后输出堆顶,用最后一个节点代替堆顶,然后从上往下撸一遍,循环输出堆顶即可。
//heap sort
#include <iostream>
using namespace std;
template<class elemType>
void exchange(elemType &a,elemType &b)
{
elemType temp=a;
a=b;
b=temp;
}
template<class elemType>
void siftAdjust(elemType elem[],int low,int high)
{
int adjust,i;//adjust is now to change
for(adjust=low,i=2*low+1;i<=high;i=2*i+1)
{
if(i<high && elem[i]<elem[i+1]) i++;//cause the right child is biger so point to the right.
if(elem[adjust]>=elem[i])break;
exchange(elem[adjust],elem[i]);
adjust=i;
}
}
template<class elemType>
void heapSort(elemType elem[],int n)
{
int i;
for(i=(n-2)/2;i>=0;i--)
{
siftAdjust(elem,i,n-1);
}
for(i=n-1;i>0;i--)
{
exchange(elem[0],elem[i]);
siftAdjust(elem,0,i-1);
}
}
int main()
{
int a[]={3,1,2,7,9,6};
heapSort(a,6);
for(int i=0;i<6;i++)
cout<<a[i]<<endl;
return 0;
}