PageRenderTime 42ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/source/library/Interlace/Collections/PriorityQueue.cs

https://bitbucket.org/VahidN/interlace
C# | 206 lines | 135 code | 43 blank | 28 comment | 14 complexity | a49ccbf48b6170860e5e8dcb9bece5f9 MD5 | raw file
  1. #region Using Directives and Copyright Notice
  2. // Copyright (c) 2007-2010, Computer Consultancy Pty Ltd
  3. // All rights reserved.
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are met:
  7. // * Redistributions of source code must retain the above copyright
  8. // notice, this list of conditions and the following disclaimer.
  9. // * Redistributions in binary form must reproduce the above copyright
  10. // notice, this list of conditions and the following disclaimer in the
  11. // documentation and/or other materials provided with the distribution.
  12. // * Neither the name of the Computer Consultancy Pty Ltd nor the
  13. // names of its contributors may be used to endorse or promote products
  14. // derived from this software without specific prior written permission.
  15. //
  16. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  19. // ARE DISCLAIMED. IN NO EVENT SHALL COMPUTER CONSULTANCY PTY LTD BE LIABLE
  20. // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  22. // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  23. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  24. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  25. // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
  26. // DAMAGE.
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Text;
  30. using Interlace.Mathematics;
  31. #endregion
  32. namespace Interlace.Collections
  33. {
  34. public class PriorityQueue<T> where T : IComparable
  35. {
  36. T[] _elements;
  37. int _elementsUsed;
  38. public PriorityQueue()
  39. : this(16)
  40. {
  41. }
  42. public PriorityQueue(int capacity)
  43. {
  44. _elements = new T[BitTricks.NextPowerOfTwo(capacity)];
  45. _elementsUsed = 0;
  46. }
  47. public int Capacity
  48. {
  49. get
  50. {
  51. return _elements.Length;
  52. }
  53. set
  54. {
  55. ReallocateToCapacity(value);
  56. }
  57. }
  58. void ReallocateToCapacity(int newCapacity)
  59. {
  60. if (newCapacity < _elementsUsed)
  61. {
  62. throw new ArgumentOutOfRangeException(
  63. "The capacity of a heap can not be less than the count.");
  64. }
  65. T[] newElements = new T[newCapacity];
  66. Array.Copy(_elements, newElements, _elementsUsed);
  67. _elements = newElements;
  68. }
  69. void EnsureThereIsCapacityForAdd()
  70. {
  71. if (_elementsUsed < Capacity) return;
  72. int roundedOldCapacity = BitTricks.NextPowerOfTwo(Capacity);
  73. int newCapacity = roundedOldCapacity * 2;
  74. ReallocateToCapacity(newCapacity);
  75. }
  76. public void TrimToSize()
  77. {
  78. Capacity = Count;
  79. }
  80. public int Count
  81. {
  82. get { return _elementsUsed; }
  83. }
  84. void Heapify(int initialRoot)
  85. {
  86. int root = initialRoot;
  87. while (true)
  88. {
  89. int left = 2 * root + 1;
  90. int right = 2 * root + 2;
  91. int smallest;
  92. smallest = left < _elementsUsed && _elements[left].CompareTo(_elements[root]) < 0 ? left : root;
  93. smallest = right < _elementsUsed && _elements[right].CompareTo(_elements[smallest]) < 0 ? right : smallest;
  94. if (smallest == root) break;
  95. T temporary = _elements[root];
  96. _elements[root] = _elements[smallest];
  97. _elements[smallest] = temporary;
  98. root = smallest;
  99. }
  100. }
  101. public T Peek()
  102. {
  103. if (_elementsUsed < 1) throw new InvalidOperationException(
  104. "Elements can not be peeked at from an empty queue.");
  105. return _elements[0];
  106. }
  107. public T Dequeue()
  108. {
  109. if (_elementsUsed < 1) throw new InvalidOperationException(
  110. "Elements can not be dequeued from an empty queue.");
  111. T element = _elements[0];
  112. _elements[0] = _elements[_elementsUsed - 1];
  113. _elementsUsed--;
  114. // Avoid keeping references in the unused array slots for the garbage collector:
  115. _elements[_elementsUsed] = default(T);
  116. Heapify(0);
  117. return element;
  118. }
  119. public void Enqueue(T element)
  120. {
  121. EnsureThereIsCapacityForAdd();
  122. // Add the element at the end, assuming for now that it is the largest:
  123. _elements[_elementsUsed] = element;
  124. _elementsUsed++;
  125. int i = _elementsUsed - 1;
  126. // Pretend to increase the element to the real value, and let it bubble up:
  127. while (i > 0 && _elements[(i - 1) / 2].CompareTo(_elements[i]) > 0)
  128. {
  129. T temporary = _elements[i];
  130. _elements[i] = _elements[(i - 1) / 2];
  131. _elements[(i - 1) / 2] = temporary;
  132. i = (i - 1) / 2;
  133. }
  134. }
  135. public bool Remove(T element)
  136. {
  137. for (int i = 0; i < _elementsUsed; i++)
  138. {
  139. if (object.Equals(element, _elements[i]))
  140. {
  141. RemoveAt(i);
  142. return true;
  143. }
  144. }
  145. return false;
  146. }
  147. void RemoveAt(int i)
  148. {
  149. while (i > 0)
  150. {
  151. T temporary = _elements[i];
  152. _elements[i] = _elements[i / 2];
  153. _elements[(i - 1) / 2] = temporary;
  154. i = (i - 1) / 2;
  155. }
  156. Dequeue();
  157. }
  158. public void Clear()
  159. {
  160. _elementsUsed = 0;
  161. }
  162. }
  163. }