数据结构算法学习-优先队列-二叉堆
优先队列定义
优先队列是至少有两种操作的数据结构:插入(Insert),删除最小者(DeleteMin)。
二叉堆定义
二叉堆抽象概念是一个完全填满的二叉树(底层可能有例外),由于父子关系很有规律(任意位置i上的元素,父亲在abs(i/2),左儿子在2i上,有儿子在2i+1上,用左移右移操作实现乘除),可以用数组实现而不需要指针(链表)。
算法实现
/* Elr Heap Int Source */ #include <stdio.h> #include <stdlib.h> #include "elr_heap_int.h" #define parent(x) (x >> 1) #define left(x) (x << 1) #define right(x) (x << 1 + 1) pHeap elrInitHeap(int capaticy) { pHeap s; s = malloc(sizeof(sHeap)); if (s == NULL) { printf("out of space!"); } s->data = malloc(sizeof(long long int) * (capaticy + 1)); if (s->data == NULL) { printf("out of space!"); } s->capacity = capaticy; s->size = 0; s->data[0] = -1; return s; } void elrFreeHeap(pHeap info) { if (info != NULL) { free(info->data); free(info); } } int elrIsHeapEmpty(pHeap info) { return info->size == 0; } int elrIsHeapFull(pHeap info) { return info->size == info->capacity; } void elrPushHeap(pHeap info, long long int value) { int i; if (elrIsHeapFull(info)) { printf("full heap"); } else { for (i = ++info->size; info->data[parent(i)] > value; i = parent(i)) { info->data[i] = info->data[parent(i)]; } info->data[i] = value; } } long long int elrFindHeapMin(pHeap info) { if (elrIsHeapEmpty(info)) { printf("empty heap"); return info->data[0]; } else { return info->data[1]; } } long long int elrDeleteHeapMin(pHeap info) { int i, child; long long int min, last; if (elrIsHeapEmpty(info)) { printf("empty heap"); return info->data[0]; } else { min = info->data[1]; last = info->data[info->size--]; for (i = 1; left(i) <= info->size; i = child) { child = left(i); if ((child != info->size) && (info->data[child] >= info->data[child + 1])) { child++; } if (last > info->data[child]) { info->data[i] = info->data[child]; } else { break; } } info->data[i] = last; return min; } }
相关推荐
ipqtjmqj 2020-02-24
Airuio 2020-02-11
shawsun 2019-12-15
风吹夏天 2019-11-03
生如蚁美如神 2019-10-23
pengkingli 2019-07-01
InitJ 2019-07-01
daklqw 2019-06-30
lickylin 2019-06-28
whtqsq 2019-06-28
张小染 2019-01-10
康慧欣 2018-08-15
hanyujianke 2017-10-27
学习小殿 2017-09-21
LHpython 2019-04-22
LHpython 2019-03-05
燕返 2019-04-11