#include<stdio.h>
#include<stdlib.h>
struct heap{
int *data;
int maxlenth,lenth;
};
struct heap*Creat(int MaxLenth){//lenth为下标,当前为0 当输入数据后,下标为最后一个元素的下标
struct heap*p;
p=(struct heap*)malloc(sizeof(struct heap));
p->maxlenth=MaxLenth;
p->lenth=0;
p->data=(int *)malloc(MaxLenth*sizeof(int) );
p->data[0]=100000;
return p;
}
void paixu(struct heap*maxheap){
int i=(maxheap->lenth)/2; //将两堆结合的根节点与大孩子进行比较,直到遇到俩孩子都比自己小,或者孩子的下标超出长度,在比较的同时也就意味着原始堆的根节点比孩子要来的小,需要往下挪,而大的孩子需要顶替原结点的位置。
int maxchild,father,child,temp,end;
for(;i>=1;i--){//进行合堆
temp=maxheap->data[i];
end=maxchild=father=i;
child=father*2;
while(child<=maxheap->lenth){//确保每次合堆都是符合堆的要求
if(child+1<=maxheap->lenth)
maxchild=maxheap->data[child]>maxheap->data[child+1]?child:child+1;
else
maxchild=child;
if(maxheap->data[maxchild]>temp){
maxheap->data[father]=maxheap->data[maxchild];
end=maxchild;
}
else
break;
father=child;
child*=2;
}
maxheap->data[end]=temp;
}
}
void print(struct heap*maxheap,int n){
printf("%d",maxheap->data[n]);
for(n/=2;n>=1;n/=2)
printf(" %d",maxheap->data[n]);
}
void print2(struct heap*maxheap){
int i=1;
printf("%d",maxheap->data[i]);
for(++i;i<=maxheap->lenth;i++)
printf(" %d",maxheap->data[i]);
}
int main(){
int N,i;
struct heap *maxheap;//最大堆
scanf("%d",&N);
maxheap=Creat(N+1);
for(i=1;i<=N;i++){
scanf("%d",&maxheap->data[++maxheap->lenth]);
}
paixu(maxheap);
print2(maxheap);
return 0;
}
堆排序的整体法判断-c
最新推荐文章于 2022-02-17 16:17:01 发布