//最大堆的建立;
看源代码:
#include <iostream>
using namespace std;
const int max=11;
int dui[max]={0,4,1,3,2,16,9,10,14,8,7};
void swap(int longest,int i)//交换函数
{
int temp;
temp=dui[i];
dui[i]=dui[longest];
dui[longest]=temp;
}
void max_heapify(int i)
{
int l=2*i;
int r=l+1;
int longest=i;
if(l<=10&&dui[l]>dui[i])
longest=l;
if(r<=10&&dui[r]>dui[longest])
longest=r;
if(longest!=i)
{
swap(longest,i);
max_heapify(longest);
}
}
void build_heap()
{
for (int i=5;i>=1;i--)//控制循环,i=5是因为5是堆中元素个数的一半,也就是10的一半
{
max_heapify(i);//建立最大堆
}
}
int main()
{
build_heap();//建堆函数
for(int i=1;i<11;i++)
cout<<dui[i]<<' ';
cout<<endl;
return 0;
}