A priority queue is a collection of zero or more elements. Each element has a priority or value.一个优先级队列是0个或者更多元素的集合。每一个元素都有一个优先级或者值
进入队列的时候有优先级,出队列优先出高优先级的.
以下我们确定元素的优先级是通过数字的大小来确定。
1.1. 优先级队列分类(根据大小)
In a min priority queue the find operation finds the element with minimum priority, while the delete operation delete this element.在最小优先级队列中,当需要删除一个元素的时候,我们找到优先级最小的元素来删除
In a max priority queue, the find operation finds the element with maximum priority, while the delete operation delete this element.在最大优先级队列中,当需要删除一个元素的时候,我们找到优先级最大的元素来删除
2. 最大优先级队列(MaxPriorityQueue)
2.1. ADT(逻辑上最大优先级队列)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
AbstractDataType MaxPriorityQueue { instances finite collection of elements,each has a priority 有限的元素的结合,每个元素都有一个优先级 operations Create(): create an empty priority queue 创建一个空的优先级队列 Size(): return number of element in the queue 返回队列中元素的个数 Max(): return element with maximum priority 返回队列中拥有最高优先级的元素 Insert(x): insert x into queue 插入x进入队列 DeleteMax(x):delete the element with largest priority from the queue; return it in x;删除队列中最高优先级的元素,并且通过x返回它 } 实现 Use an unordered linear list 我们使用无序线性表来进行实现 Insertions are performed at the right end of the list, θ(1) 插入元素到链表的最右边(时间复杂度为常数) A deletion requires a search for the element with largest priority, θ(n)(需要查找到最高优先级的元素并且删除这个元素)
2.2. 物理实现:Heap
A max heap(min Heap):(最大堆)
is A complete binary tree 最大堆是一个完全二叉树
The value in each node is greater(less) than or equal to those in its children(if any).每一个节点上的值都大于(小于)或者等于他的子节点(如果有的话)
注意:完全二叉树可以用矩阵来进行存储。
从上向下一层一层进行记录。
2.3. 实现:最大优先级队列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
template<classT>classMaxHeap { public: MaxHeap(int MaxHeapSize=10); ~MaxHeap(){delete[]heap;} intsize()const{return CurrentSize;} T Max(){ if (CurrentSize==0) throwOutOfBounds(); return heap[1]; } MaxHeap<T>&insert(const T&x); MaxHeap<T>& DeleteMax(T& x); voidinitialize(T a[], int size, int ArraySize); private: int CurrentSize, MaxSize; T * heap; }
评论