堆排序的整体法判断-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 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;
 
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值