优先队列(堆)
来源:互联网 发布:linux awk 编辑:程序博客网 时间:2024/05/21 10:15
一个优先队列的实现:
#include <iostream>#define MAXSIZE 100typedef struct heap { int size; int capacity; int* a;}Heap;Heap heap;void initHeap() { heap.size = 0; heap.capacity = MAXSIZE; heap.a = new int[MAXSIZE];}void insert(int data) { heap.size += 1; heap.a[heap.size] = data; int index = heap.size; for(; index > 1; index = index / 2) { if(heap.a[index] < heap.a[index/2]) { int tmp = heap.a[index]; heap.a[index] = heap.a[index/2]; heap.a[index/2] = tmp; } else { break; } }}int deleteMin() { int min = heap.a[1]; int i = 1; int index = 1; int lastData = heap.a[heap.size]; while(true) { if(i*2+1 <= heap.size) { if(heap.a[i*2] < heap.a[i*2+1]) { heap.a[i] = heap.a[i*2]; i = i*2; } else { heap.a[i] = heap.a[i*2+1]; i = i*2+1; } } else if(i*2 <= heap.size) { heap.a[i] = heap.a[i*2]; i = i*2; } else { break; } } heap.a[i] = lastData; heap.size -= 1; return min;}void print() { for(int i=1; i <= heap.size; i++) { std::cout << heap.a[i] << ","; std::cout << std::endl; }}int main() { initHeap(); insert(9); insert(8); insert(7); insert(6); insert(5); insert(4); //print(); deleteMin(); print(); return 0;}
堆是一棵被完全填满的二叉树(完全二叉树),它的任意节点小于它的子节点,它的插入,删除操作时间复杂度为O(log2N);
阅读全文
0 0
- 优先队列(堆)
- 优先队列(堆)
- 优先队列(堆)
- 优先队列(堆)
- 优先队列(堆)
- 优先队列(堆)
- 优先队列(堆)
- 优先队列(堆)
- 优先队列(堆)
- 二叉堆(优先队列)
- 二叉堆(优先队列)
- 数据结构---->优先队列(堆)
- 优先队列(堆)目录
- 优先队列(堆)浅谈
- 优先队列(最小堆)
- 二叉堆(优先队列)
- [数据结构].堆(优先队列)
- 堆排序(优先队列)
- 过滤器
- Cantor三分集的递归算法
- 欢迎使用CSDN-markdown编辑器
- 屏蔽刷postfix IP的脚本
- session一致性架构设计实践
- 优先队列(堆)
- 保留或不保留两位小数,数字分割或不分割
- MFC应用程序WinMain函数
- 2017计蒜客比赛第二场A题B题
- 树莓派GPIO
- java垃圾回收算法之-标记压缩
- UVa NO.10006 Carmichael Numbers
- Hyperledger Fabric V1.0学习之一---在mac上配置hyperledger fabric
- 找出不在预定数组中的自然数