搬运自我的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 }
原文地址:https://www.cnblogs.com/lyrich/p/10960729.html
时间: 2024-11-01 14:48:18