码迷,mamicode.com
首页 > 其他好文 > 详细

写给自己看的二叉堆(1):基本操作

时间:2019-06-01 21:38:23      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:detail   creat   col   log   定义   https   完全   one   blog   

搬运自我的CSDN https://blog.csdn.net/u013213111/article/details/90343879

也就是一棵完全二叉树。堆顶最大则为大根堆,堆顶最小则为小根堆,这里实现的是小根堆。
1.定义
用一个数组来存储数据。

1 typedef int eletype;
2 
3 typedef struct heapstruct
4 {
5     int capacity;
6     int size;
7     eletype *arr; //used for saving data
8 }Heap;

2.新建一个二叉堆
给二叉堆分配空间,给存储数据用的数组分配空间。

 1 Heap *CreateHeap(int max)
 2 {
 3     Heap *H;
 4     H = malloc(sizeof(Heap));
 5     if (H == NULL) {
 6         printf("Out of space\n");
 7         return NULL;
 8     }
 9 
10     H->arr = malloc(sizeof(eletype) * (max + 1));
11     if (H->arr == NULL) {
12         printf("Out of space\n");
13         return NULL;
14     }
15 
16     H->capacity = max;
17     H->size = 0;
18     H->arr[0] = 0;
19 
20     return H;
21 }

3.插入
上滤找到合适的插入位置。

 1 eletype DeleteMin(Heap *H)
 2 {
 3     if (H->size == 0) {
 4         printf("Heap is empty\n");
 5         return 0;
 6     }
 7     eletype min = H->arr[1];
 8     eletype last = H->arr[H->size--]; //--!
 9     int i, child;
10     for(i = 1; i * 2 <= H->size; i = child) {
11         //Find smaller child
12         child = i * 2;
13         if (child != H->size && H->arr[child + 1] < H->arr[child])
14             child++;
15         //precolate one leve
16         if (last > H->arr[child])
17             H->arr[i] = H->arr[child];
18         else
19             break;
20     }
21     H->arr[i] = last;
22     return min;
23 }

4.删除最小元素(堆顶)
为了保证删除后仍是一个完整的二叉堆,要将原堆顶以下的数据进行适当的上滤。

 1 eletype DeleteMin(Heap *H)
 2 {
 3     if (H->size == 0) {
 4         printf("Heap is empty\n");
 5         return 0;
 6     }
 7     eletype min = H->arr[1];
 8     eletype last = H->arr[H->size--]; //--!
 9     int i, child;
10     for(i = 1; i * 2 <= H->size; i = child) {
11         //Find smaller child
12         child = i * 2;
13         if (child != H->size && H->arr[child + 1] < H->arr[child])
14             child++;
15         //precolate one leve
16         if (last > H->arr[child])
17             H->arr[i] = H->arr[child];
18         else
19             break;
20     }
21     H->arr[i] = last;
22     return min;
23 }

 

写给自己看的二叉堆(1):基本操作

标签:detail   creat   col   log   定义   https   完全   one   blog   

原文地址:https://www.cnblogs.com/lyrich/p/10960729.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!