堆(优先队列)的构建以及基本操作实现
2017-12-07 09:00
218 查看
//构建一个堆(优先队列),采用顺序存储 //增删都是在顺序存储的尾端进行,push操作需要向上调整 //pop操作需要向下调整,堆的构建过程是,将构建堆所需要 //的数组顺序放在heap的连续存储空间内,然后从最尾端的 //度为2的节点开始向下调整,一直到根节点 class Heap { public: int *heap; int maxSize; int lenth; public: Heap()= default; Heap(int size,int *a,int n); ~Heap(); void shiftDown(int ); void shiftUp(int); bool pop(int &); bool push(int ); }; Heap::~Heap() { delete[] heap; } Heap::Heap(int size,int *a,int n) { maxSize = size; heap = new int[size]; lenth = n; for(int i =0; i<n;i++) { heap[i] = a[i]; } for(int i = n/2 -1;i>=0;i++) shiftDown(i); } void Heap::shiftUp(int a) { if(a > lenth - 1 || a < 0) return; int p = a; int uper = (a - 1)/2; while (uper >= 0) { if(heap[p] < heap[uper]) return; int temp = heap[p]; heap[p] = heap[uper]; heap[uper] = temp; p = uper; } } void Heap::shiftDown(int a) { int i = a; //标识父节点 int j = 2*i + 1; //标识左子节点 int temp = heap[i]; while(j < lenth) { if((j < lenth -1) && heap[j+1]>heap[j]) j++; if(temp < heap[j]) { heap[i] = heap[j]; i = j; j = 2*j + 1; } else break; } heap[i] = temp; } bool Heap::pop(int & a) { if(lenth <= 0) return false; a = heap[0]; heap[0] = heap[lenth - 1]; lenth --; shiftDown(0); return true; } bool Heap::push(int a) { if(lenth == maxSize) return false; heap[++lenth] = a; shiftUp(lenth - 1); return true; }
相关文章推荐
- 【 数据结构】实现二叉树以及其基本操作
- MapReduce实现基本SQL操作的原理-join和group by,以及Dinstinct
- 实验4:栈和队列的基本操作实现及其应用——进制转换以及实验总结
- 数据结构-堆基本概念以及操作实现
- KD-tree的原理以及构建与查询操作的python实现
- 数据结构中栈的实现以及其基本操作
- 树的基本结构,以及利用链表实现树的各项操作(创建、添加/删除/打印树节点、销毁等等)
- 字符流的基本实现以及编码问题之读操作
- 二叉树的基本操作以及相关问题的求解—C++实现
- 图的基本操作及BFS与DFS的实现以及飞机换乘问题
- Redis缓存系统(1)Java-Jedis操作Redis,基本操作以及 实现对象保存
- Redis缓存系统(一)Java-Jedis操作Redis,基本操作以及 实现对象保存
- 链表的java实现以及基本的增加,删除,排序操作
- KD-tree的原理以及构建与查询操作的python实现
- 使用express.js框架一步步实现基本应用以及构建可扩展的web应用
- 【转载】MapReduce实现基本SQL操作的原理-join和group by,以及Dinstinct
- (C语言版)栈和队列(一)——实现链式栈和链式队列的基本操作以及遇到的问题
- SBTree的左旋右旋以及各种调整操作的基本实现(包含查找第k大的数值)
- KD-tree的原理以及构建与查询操作的python实现
- Redis缓存 ava-Jedis操作Redis,基本操作以及 实现对象保存