C源码@数据结构与算法->PriorityQueues
2015-08-22 16:39
417 查看
/* * binheap.cpp */ #include <stdlib.h> #include "fatal.h" #include "binheap.h" #define MinPQSize (10) #define MinData (-32767) struct HeapStruct { int Capacity; int Size; ElementType *Elements; }; PriorityQueue Initialize(int MaxElements) { PriorityQueue H; if (MaxElements < MinPQSize) { FatalError("Priority queue size is too small!"); } H = (PriorityQueue)malloc(sizeof(struct HeapStruct)); if (H == NULL) { FatalError("Out of space!"); } /* Allocate the array plus one extra for sentinel */ H->Elements = (ElementType *)malloc(sizeof(ElementType) * (MaxElements + 1)); if (H->Elements == NULL) { FatalError("Out of space!"); } H->Capacity = MaxElements; H->Size = 0; H->Elements[0] = MinData; return H; } void MakeEmpty(PriorityQueue H) { H->Size = 0; } int IsEmpty(PriorityQueue H) { return H->Size == 0; } int IsFull(PriorityQueue H) { return H->Size == H->Capacity; } /* * H->Elements[0] is a sentinel. * * Heap Order Proprety: * In a heap, for every node x, the key in the parent of X is smaller than * (or equal to) the key in X, with the exception of the root(which has no parent). */ void Insert(ElementType X, PriorityQueue H) { int i; if (IsFull(H)) { FatalError("Priority queue is full!"); } for (i = ++H->Size; H->Elements[i / 2] > X; i /= 2) { H->Elements[i] = H->Elements[i / 2]; } H->Elements[i] = X; } ElementType DeleteMin(PriorityQueue H) { int i, Child; ElementType MinElement, LastElement; if (IsEmpty(H)) { FatalError("Priority queue is empty!"); } MinElement = H->Elements[1]; LastElement = H->Elements[H->Size--]; for (i = 1; i * 2 <= H->Size; i = Child) { /* Find smaller child */ Child = i * 2; if (Child != H->Size && H->Elements[Child + 1] < H->Elements[Child]) { Child++; } /* Percolate one level */ if (LastElement > H->Elements[Child]) { H->Elements[i] = H->Elements[Child]; } else { break; } } H->Elements[i] = LastElement; return MinElement; } ElementType FindMin(PriorityQueue H) { if (!IsEmpty(H)) { return H->Elements[1]; } else { FatalError("Priority queue is empty!"); return -1; /* Just for avoid warning */ } } void Destroy(PriorityQueue H) { free(H->Elements); free(H); }
相关文章推荐
- 数据结构学习笔记之递归+汉诺塔
- 【C++/数据结构】双向链表的基本操作
- 【c++版数据结构】之循环双链表的实现(带头结点以及尾节点)
- 【C++/数据结构】循环链表的基本操作
- 【C++/数据结构】单链表的基本操作
- 【C++/数据结构】顺序表的基本操作
- 数据结构课程的实践方法指导
- 数据结构实验之图论二:基于邻接表的广度优先搜索遍历 (BFS)
- STL中map、set的数据结构及底层实现
- 数据结构基础 哈希表 概念篇
- 数据结构-图的创建与遍历
- 代写代做程序设计 国外算法编程 VB/C语言/C++/数据结构/Java/PHP/Python
- 数据结构学习笔记之队列
- 数据结构绪论1
- 数据结构之---C语言实现最短路径之Floyd(弗洛伊德)算法
- 数据结构-二叉树定义
- 《数据结构与算法分析》引论:选择问题实现
- 【c++版数据结构】之双链表的实现(带头结点以及尾节点)
- 【c++版数据结构】之循环单链表的实现(带头结点以及尾节点)
- MySQL索引背后的数据结构及算法原理