插入法建堆
#include<bits/stdc++.h>
using namespace std;
void insertHeap(int a[],int pos)
{
while(1)
{
int fath = (pos+1)/2-1;
if(a[pos]>a[pos-1])
{
if(a[pos]>a[fath]&&fath>=0)
{
int tmp = a[fath];
a[fath] = a[pos];
a[pos] = tmp;
pos = fath;
}
}
else
break;
}
}
void BuildMaxHeap(int a[],int len)
{
if(len<2)
{
cout<<"heapsize is too little"<<endl;
return;
}
for(int i=1; i<len; i++)
{
insertHeap(a,i);
for(int i=0; i<len; i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
}
}
int main()
{
int a[]= {2,3,1,5,8,9,0};
int len = sizeof(a)/sizeof(a[0]);
BuildMaxHeap(a,len);
for(int i=0; i<len; i++)
{
cout<<a[i]<<" ";
}
}