堆与优先队列

分析与思考

数组是完全二叉树的存储结构,完全二叉树是数组的逻辑结构,这样我们就可以使用树形结构来解决线性问题。


  • 大顶堆(用于升序排序,根节点大于等于两个子节点)
  • 小顶堆(用于降序排序,根节点小于等于两个子节点)

堆的插入与删除:尾部插入,头部弹出(联想到了队列
不同编程语言在实现优先队列时底层90%是由堆构成的。


通过代码本身来提高编程能力是错误的,应注重思维逻辑结构的提升


数据结构 = 结构定义 + 结构操作


演示代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
typedef struct Heap {
    int *data;
    int n, size;
} Heap;

Heap *init(int n);
void clear(Heap *);
void push(Heap *, int);
void pop(Heap *);
void output(Heap *);
int main(){
    srand(time(0));
    Heap *p = init(21);
    for (int i = 0; i < 20; ++i) {
        int value = rand() % 100;
        printf("insert %d to heap\n", value);
        push(p, value);
        output(p);
    }
    for (int i = 0; i < 20; ++i) {
        pop(p);
        output(p);   
    }
    clear(p);
    return 0;
}

Heap * init(int n) {
    Heap *p = (Heap *)malloc(sizeof(Heap));
    p->data = (int *)malloc(sizeof(int) * n);
    memset(p->data, 0 , sizeof(p->data));
    p->size = n;
    p->n = 0;
    return p;
}

void clear(Heap *h) {
    if (h == NULL) return;
    free(h->data);
    free(h);
    return;
}

void push(Heap *h, int value) {
    if (h->n == h->size) return;
    h->n += 1;
    h->data[h->n] = value;
    int i = h->n;
    while (i > 1) {
        if (h->data[i] <= h->data[i / 2]) break;
        h->data[i] ^= h->data[i / 2];
        h->data[i / 2] ^= h->data[i];
        h->data[i] ^= h->data[i / 2];
        i /= 2;
    }
    return ;
}
void pop(Heap *h) {
    if (h->n <= 1) {
        h->n = 0;
        return;
    }
    h->data[1] ^= h->data[h->n];
    h->data[h->n] ^= h->data[1];
    h->data[1] ^= h->data[h->n];
    h->n -= 1;
    int ind = 1;
    while (ind * 2 <= h->n) {
        int swap_ind = ind * 2;
        if (h->data[ind * 2] > h->data[swap_ind]) swap_ind = ind * 2;
        if (ind * 2 + 1 <= h->n && h->data[ind * 2 + 1] > h->data[swap_ind])
            swap_ind = ind * 2 + 1;
        if (swap_ind == ind) break;
        h->data[ind] ^= h->data[swap_ind];
        h->data[swap_ind] ^= h->data[ind];
        h->data[ind] ^= h->data[swap_ind];
        ind = swap_ind;
    }
    return;
}

void output(Heap *h) {
    printf("Heap = [");
    for (int i = 1; i < h->size; ++i) {
        printf("%d, ", h->data[i]);
    }
    printf("]\n");
    return;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值