背景
此文给出基于已排序数组的实现,多数情况应该基于 Heap 进行实现,因为数组的插入效率为O(n),而 Heap 的插入效率为 Log(n)。
PriorityQueue
代码
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace DataStuctureStudy.Queues 8 { 9 public class PriorityQueue<T> 10 where T : IComparable<T> 11 { 12 private readonly int _maxSize; 13 private readonly T[] _items; 14 private int _count = 0; 15 private int _head = -1; 16 17 public PriorityQueue(int size) 18 { 19 _maxSize = size; 20 _items = new T[size]; 21 } 22 23 public void EnQueue(T item) 24 { 25 if (this.IsFull()) 26 { 27 throw new InvalidOperationException("队列已满"); 28 } 29 30 if (_count == 0) 31 { 32 _items[++_head] = item; 33 } 34 else 35 { 36 _items[++_head] = item; 37 for (var i = _head; i >= 1; i++) 38 { 39 if (_items[i].CompareTo(item) < 0) 40 { 41 Swap(_items, i - 1, i); 42 } 43 else 44 { 45 break; 46 } 47 } 48 } 49 50 _count++; 51 } 52 53 public T DeQueue() 54 { 55 if (this.IsEmpty()) 56 { 57 throw new InvalidOperationException("队列已空"); 58 } 59 60 T item = _items[_head--]; 61 62 _count--; 63 64 return item; 65 } 66 67 public T Peek() 68 { 69 if (this.IsEmpty()) 70 { 71 throw new InvalidOperationException("队列已空"); 72 } 73 74 return _items[_head]; 75 } 76 77 public bool IsFull() 78 { 79 return _count == _maxSize; 80 } 81 82 public bool IsEmpty() 83 { 84 return _count == 0; 85 } 86 87 public int Size() 88 { 89 return _count; 90 } 91 92 private static void Swap(T[] items, int left, int right) 93 { 94 if (left != right) 95 { 96 var temp = items[left]; 97 items[left] = items[right]; 98 items[right] = temp; 99 } 100 } 101 } 102 }