最大堆和堆排序

最大堆

#define maxdata 10000000

struct heapstruct
{
    elementtype *elements;  //存储堆元素的数组 
    int size;       //堆的当前元素个数 
    int capacity;   //堆的最大容量 
};

最大堆的建立

struct heapstcuct *create(int maxsize) 
{   //创建容量为maxsize的空的最大堆 
    struct heapstruct *h;
    h =(struct heapstruct *)malloc(sizeof(struct heapstruct));
    
    h->elements =(elementtype *)malloc((maxsize+1)*sizeof(elementtype))
    h->size = 0;
    h->capacity = maxsize;
    h->elements[0] = maxdata;
    //定义"哨兵"位大于堆中所有可能元素的值,便于以后更快操作 
    return h;
}

最大堆的元素插入

void insert(struct heapstruct *h, elementtype item)
{   //元素item插入最大堆h,其中h->element[0]已经定义为哨兵 
    int i;
    if(isfull(h))
    {
        printf("最大堆已满!");
        return ;
    }
    
    i = ++h->size;  //i指向插入后堆中最后一个元素的位置 
    for(; h->elements[i/2] < item; i /= 2 )
    {
        h->elements[i] = h->elements[i/2];  //向下过滤节点 
    }
    h->elements[i] = item;
}

最大堆的元素删除


elementtype deletemax(struct heapstruct *h)
{   //从最大堆h中取出键值为最大的元素,并删除一个节点 
    int parent, children;
    elementtype maxitem, tmp;
    if(isempty(h))
    {
        printf("最大堆已空!");
        return ;
    }
    
    maxitem = h->elements[1];  //取出根节点最大值 
    //用最大堆中最后一个元素从根节点开始向上过滤下层结点 
    tmp = h->elements[h->size--]; 
    
    for(parent = 1; parent * 2 <= h->size; parent = child)
    {
        child = parent * 2;
        if((child != h->size) && (h->elements[child] < h->elements[child + 1]))
        {
            child++;  //child指向左右子节点的较大者 
        }
        
        if(tmp >= h->elements[child])
        {
            break;
        }
        else  //移动tmp元素到下一层 
        {
            h->elements[parent] = h->elements[child];
        }
    }
    
    h->elements[parent] = tmp;
    
    return maxitem;
}
 

 

堆排序

void heap(elementtype a[], int n)
{
    buildheap(a);               // 建一个最小堆 O(N)  
    
    for(i = 0; i < n; i++)
    {
        tmp[i] = deleteheap(a); // O(log(N))
    }
    
    for(i = 0; i < n; i++)
    {
        a[i] = tmp[i];          // O(N)
    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值