最大堆

//最大堆
//用完全二叉树来存储堆,因为是完全二叉树,所以用顺序表比较方便
#include<stdio.h>
#include<stdlib.h>
#define Maxdata 10000
typedef int Elemtype;
//用顺序表来存储
typedef struct HeadStuct{
    Elemtype *data;
    int Size;
    int Capacity;
}*MaxHeap;
//创建堆
MaxHeap Creat(int MaxSize)
{
    MaxHeap H=(struct HeadStuct *)malloc(sizeof(struct HeadStuct));
    H->data=(Elemtype *)malloc((MaxSize+1)*sizeof(Elemtype));
    H->Size=0;
    H->Capacity=MaxSize;
    H->data[0]=Maxdata;//定义哨兵,大于堆中所有元素,那么插入时少一个判断条件,加快效率
    return H;
}
//判断数组是否满了
int isFull(MaxHeap H)
{
    return H->Size==H->Capacity;
}
//插入
void Insert(Elemtype x,MaxHeap H)
{
    int i;
    if(isFull(H))
    {
        printf("This heap is ful\n");
        return ;
    }
    i=++H->Size;
    while(x>H->data[i/2])//因为有一个哨兵,输入的值都小于哨兵,所以不用判断i>1
    {
        H->data[i]=H->data[i/2];
        i/=2;
    }
    H->data[i]=x;
}
//判断是否为空
int isEmpty(MaxHeap H)
{
    return H->Size==0;
}
//删除最大元素
Elemtype DeleteMax(MaxHeap H)
{
    Elemtype temp,Maxitem;
    int parent,child;
    if(isFull(H))
    {
        printf("This heap is empty\n");
        return 0;
    }
    Maxitem=H->data[1];
    temp=H->data[H->Size--];
    for(parent=1;parent*2<=H->Size;parent=child)
    {
        child=parent*2;
        if(parent!=H->Size&&(H->data[child]<H->data[child+1]))//parent!=H->Size的原因是:这样做H结点才有右子树,才有后面的条件比较的必要
            child++;
        if(temp>=H->data[child])
            break;
        else
            H->data[parent]=H->data[child];
        parent=child;
    }
    H->data[parent]=temp;
    return Maxitem;
}
//调整交换
void swap(int i,int max,MaxHeap H)
{
    Elemtype t=H->data[i];
    H->data[i]=H->data[max];
    H->data[max]=t;
}
//调整
void HeapAdjust(MaxHeap H,int i)
{
    int lchild=i*2;
    int rchild=i*2+1;
    int max=i;
    if(i<=H->Size/2)
    {
        if(lchild<=H->Size&&H->data[lchild]>H->data[max])
            max=lchild;
        if(rchild<=H->Size&&H->data[rchild]>H->data[max])
            max=rchild;
        if(max!=i){
            swap(i,max,H);
            HeapAdjust(H,max);
        }
    }
}
int main()
{
    MaxHeap H;
    int MaxSize;
    scanf("%d",&MaxSize);
//    int item;
    int cnt=1;
    H=Creat(MaxSize);
//    while(scanf("%d",&item)&&item)
//        Insert(item,H);
    while(scanf("%d",&H->data[cnt])&&H->data[cnt]){cnt++;H->Size++;}
    for(int i=H->Size/2;i>=1;i--)
        HeapAdjust(H,i);
    for(int i=1;i<=H->Size;i++)
        printf("%3d",H->data[i]);
    printf("\n");
    DeleteMax(H);
    for(int i=1;i<=H->Size;i++)
        printf("%3d",H->data[i]);
    printf("\n");
    return 0;
}


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭