堆的插入排序法 C

#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 father,child,i;
    int temp=maxheap->data[maxheap->lenth];
    i=child=maxheap->lenth;
    father=child/2;
    for(;father>=1;){
        if(temp<maxheap->data[father]){
            maxheap->data[child]=maxheap->data[father];
            i=child=father;
            father=child/2;
        }
        else
            break;
    }
    maxheap->data[i]=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]);
    printf("\n");
}



int main(){
    int N,i,M,n;
    struct heap *maxheap;//最大堆
    scanf("%d",&N);
    scanf("%d",&M);
    maxheap=Creat(N+1);
    for(i=1;i<=N;i++){
        scanf("%d",&maxheap->data[++maxheap->lenth]);
        paixu(maxheap);
    }
   for(i=0;i<M;i++){
        scanf("%d",&n);
        print(maxheap,n);
    }
 
    return 0;
 
}

其中用maxheap注释了最小堆,是因为题目原因,懒得修改,实际上是最小堆的算法,转换成最大堆无非是改一下判断符号 影响不大。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值