c语言实现最大堆关键代码 --自用板子(考试用)
代码
下面展示 关键代码
。
int q[maxn],tot;
int a[maxn];
void insert(int x){
q[++tot]=x;
int fa=tot/2;
int pos=tot;
while(q[fa]<x){
q[pos]=q[fa];
q[fa]=x;
fa/=2;
pos/=2;
}
}
int top(){
return q[1];
}
void pop(){
int tmp=q[tot--];
int fa=1,child;
for(child=fa*2;child<=tot;child=fa*2){
if(child+1<=tot&&q[child]<q[child+1])child++;
if(q[child]>tmp){
q[fa]=q[child];
fa=child;
}else
break;
}
q[fa]=tmp;
}
测试
10
5 4 8 9 7 0 5 123 76 8
123 76 9 8 8 7 5 5 4 0
Program ended with exit code: 0
效果达到 ok!
最小堆代码微调即可,有空更新