MinHeap.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  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 OpenSimulator Project 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 DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Threading;
  29. using System.Collections;
  30. using System.Collections.Generic;
  31. using System.Runtime.InteropServices;
  32. namespace OpenSim.Framework
  33. {
  34. public interface IHandle { }
  35. [Serializable, ComVisible(false)]
  36. public class MinHeap<T> : ICollection<T>, ICollection
  37. {
  38. private class Handle : IHandle
  39. {
  40. internal int index = -1;
  41. internal MinHeap<T> heap = null;
  42. internal void Clear()
  43. {
  44. this.index = -1;
  45. this.heap = null;
  46. }
  47. }
  48. private struct HeapItem
  49. {
  50. internal T value;
  51. internal Handle handle;
  52. internal HeapItem(T value, Handle handle)
  53. {
  54. this.value = value;
  55. this.handle = handle;
  56. }
  57. internal void Clear()
  58. {
  59. this.value = default(T);
  60. if (this.handle != null)
  61. {
  62. this.handle.Clear();
  63. this.handle = null;
  64. }
  65. }
  66. }
  67. public const int DEFAULT_CAPACITY = 4;
  68. private HeapItem[] items;
  69. private int size;
  70. private object sync_root;
  71. private int version;
  72. private Comparison<T> comparison;
  73. public MinHeap() : this(DEFAULT_CAPACITY, Comparer<T>.Default) { }
  74. public MinHeap(int capacity) : this(capacity, Comparer<T>.Default) { }
  75. public MinHeap(IComparer<T> comparer) : this(DEFAULT_CAPACITY, comparer) { }
  76. public MinHeap(int capacity, IComparer<T> comparer) :
  77. this(capacity, new Comparison<T>(comparer.Compare)) { }
  78. public MinHeap(Comparison<T> comparison) : this(DEFAULT_CAPACITY, comparison) { }
  79. public MinHeap(int capacity, Comparison<T> comparison)
  80. {
  81. this.items = new HeapItem[capacity];
  82. this.comparison = comparison;
  83. this.size = this.version = 0;
  84. }
  85. public int Count { get { return this.size; } }
  86. public bool IsReadOnly { get { return false; } }
  87. public bool IsSynchronized { get { return false; } }
  88. public T this[IHandle key]
  89. {
  90. get
  91. {
  92. Handle handle = ValidateThisHandle(key);
  93. return this.items[handle.index].value;
  94. }
  95. set
  96. {
  97. Handle handle = ValidateThisHandle(key);
  98. this.items[handle.index].value = value;
  99. if (!BubbleUp(handle.index))
  100. BubbleDown(handle.index);
  101. }
  102. }
  103. public object SyncRoot
  104. {
  105. get
  106. {
  107. if (this.sync_root == null)
  108. Interlocked.CompareExchange<object>(ref this.sync_root, new object(), null);
  109. return this.sync_root;
  110. }
  111. }
  112. private Handle ValidateHandle(IHandle ihandle)
  113. {
  114. if (ihandle == null)
  115. throw new ArgumentNullException("handle");
  116. Handle handle = ihandle as Handle;
  117. if (handle == null)
  118. throw new InvalidOperationException("handle is not valid");
  119. return handle;
  120. }
  121. private Handle ValidateThisHandle(IHandle ihandle)
  122. {
  123. Handle handle = ValidateHandle(ihandle);
  124. if (!object.ReferenceEquals(handle.heap, this))
  125. throw new InvalidOperationException("handle is not valid for this heap");
  126. if (handle.index < 0)
  127. throw new InvalidOperationException("handle is not associated to a value");
  128. return handle;
  129. }
  130. private void Set(HeapItem item, int index)
  131. {
  132. this.items[index] = item;
  133. if (item.handle != null)
  134. item.handle.index = index;
  135. }
  136. private bool BubbleUp(int index)
  137. {
  138. HeapItem item = this.items[index];
  139. int current, parent;
  140. for (current = index, parent = (current - 1) / 2;
  141. (current > 0) && (this.comparison(this.items[parent].value, item.value)) > 0;
  142. current = parent, parent = (current - 1) / 2)
  143. {
  144. Set(this.items[parent], current);
  145. }
  146. if (current != index)
  147. {
  148. Set(item, current);
  149. ++this.version;
  150. return true;
  151. }
  152. return false;
  153. }
  154. private void BubbleDown(int index)
  155. {
  156. HeapItem item = this.items[index];
  157. int current, child;
  158. for (current = index, child = (2 * current) + 1;
  159. current < this.size / 2;
  160. current = child, child = (2 * current) + 1)
  161. {
  162. if ((child < this.size - 1) && this.comparison(this.items[child].value, this.items[child + 1].value) > 0)
  163. ++child;
  164. if (this.comparison(this.items[child].value, item.value) >= 0)
  165. break;
  166. Set(this.items[child], current);
  167. }
  168. if (current != index)
  169. {
  170. Set(item, current);
  171. ++this.version;
  172. }
  173. }
  174. public bool TryGetValue(IHandle key, out T value)
  175. {
  176. Handle handle = ValidateHandle(key);
  177. if (handle.index > -1)
  178. {
  179. value = this.items[handle.index].value;
  180. return true;
  181. }
  182. value = default(T);
  183. return false;
  184. }
  185. public bool ContainsHandle(IHandle ihandle)
  186. {
  187. Handle handle = ValidateHandle(ihandle);
  188. return object.ReferenceEquals(handle.heap, this) && handle.index > -1;
  189. }
  190. public void Add(T value, ref IHandle handle)
  191. {
  192. if (handle == null)
  193. handle = new Handle();
  194. Add(value, handle);
  195. }
  196. public void Add(T value, IHandle ihandle)
  197. {
  198. if (this.size == this.items.Length)
  199. {
  200. int capacity = (int)((this.items.Length * 200L) / 100L);
  201. if (capacity < (this.items.Length + DEFAULT_CAPACITY))
  202. capacity = this.items.Length + DEFAULT_CAPACITY;
  203. Array.Resize<HeapItem>(ref this.items, capacity);
  204. }
  205. Handle handle = null;
  206. if (ihandle != null)
  207. {
  208. handle = ValidateHandle(ihandle);
  209. handle.heap = this;
  210. }
  211. HeapItem item = new MinHeap<T>.HeapItem(value, handle);
  212. Set(item, this.size);
  213. BubbleUp(this.size++);
  214. }
  215. public void Add(T value)
  216. {
  217. Add(value, null);
  218. }
  219. public T Min()
  220. {
  221. if (this.size == 0)
  222. throw new InvalidOperationException("Heap is empty");
  223. return this.items[0].value;
  224. }
  225. public void Clear()
  226. {
  227. for (int index = 0; index < this.size; ++index)
  228. this.items[index].Clear();
  229. this.size = 0;
  230. ++this.version;
  231. }
  232. public void TrimExcess()
  233. {
  234. int length = (int)(this.items.Length * 0.9);
  235. if (this.size < length)
  236. Array.Resize<HeapItem>(ref this.items, Math.Min(this.size, DEFAULT_CAPACITY));
  237. }
  238. private void RemoveAt(int index)
  239. {
  240. if (this.size == 0)
  241. throw new InvalidOperationException("Heap is empty");
  242. if (index >= this.size)
  243. throw new ArgumentOutOfRangeException("index");
  244. this.items[index].Clear();
  245. if (--this.size > 0 && index != this.size)
  246. {
  247. Set(this.items[this.size], index);
  248. if (!BubbleUp(index))
  249. BubbleDown(index);
  250. }
  251. }
  252. public T RemoveMin()
  253. {
  254. if (this.size == 0)
  255. throw new InvalidOperationException("Heap is empty");
  256. HeapItem item = this.items[0];
  257. RemoveAt(0);
  258. return item.value;
  259. }
  260. public T Remove(IHandle ihandle)
  261. {
  262. Handle handle = ValidateThisHandle(ihandle);
  263. HeapItem item = this.items[handle.index];
  264. RemoveAt(handle.index);
  265. return item.value;
  266. }
  267. private int GetIndex(T value)
  268. {
  269. EqualityComparer<T> comparer = EqualityComparer<T>.Default;
  270. int index;
  271. for (index = 0; index < this.size; ++index)
  272. {
  273. if (comparer.Equals(this.items[index].value, value))
  274. return index;
  275. }
  276. return -1;
  277. }
  278. public bool Contains(T value)
  279. {
  280. return GetIndex(value) != -1;
  281. }
  282. public bool Remove(T value)
  283. {
  284. int index = GetIndex(value);
  285. if (index != -1)
  286. {
  287. RemoveAt(index);
  288. return true;
  289. }
  290. return false;
  291. }
  292. public void CopyTo(T[] array, int index)
  293. {
  294. if (array == null)
  295. throw new ArgumentNullException("array");
  296. if (array.Rank != 1)
  297. throw new ArgumentException("Multidimensional array not supported");
  298. if (array.GetLowerBound(0) != 0)
  299. throw new ArgumentException("Non-zero lower bound array not supported");
  300. int length = array.Length;
  301. if ((index < 0) || (index > length))
  302. throw new ArgumentOutOfRangeException("index");
  303. if ((length - index) < this.size)
  304. throw new ArgumentException("Not enough space available in array starting at index");
  305. for (int i = 0; i < this.size; ++i)
  306. array[index + i] = this.items[i].value;
  307. }
  308. public void CopyTo(Array array, int index)
  309. {
  310. if (array == null)
  311. throw new ArgumentNullException("array");
  312. if (array.Rank != 1)
  313. throw new ArgumentException("Multidimensional array not supported");
  314. if (array.GetLowerBound(0) != 0)
  315. throw new ArgumentException("Non-zero lower bound array not supported");
  316. int length = array.Length;
  317. if ((index < 0) || (index > length))
  318. throw new ArgumentOutOfRangeException("index");
  319. if ((length - index) < this.size)
  320. throw new ArgumentException("Not enough space available in array starting at index");
  321. try
  322. {
  323. for (int i = 0; i < this.size; ++i)
  324. array.SetValue(this.items[i].value, index + i);
  325. }
  326. catch (ArrayTypeMismatchException)
  327. {
  328. throw new ArgumentException("Invalid array type");
  329. }
  330. }
  331. public IEnumerator<T> GetEnumerator()
  332. {
  333. int version = this.version;
  334. for (int index = 0; index < this.size; ++index)
  335. {
  336. if (version != this.version)
  337. throw new InvalidOperationException("Heap was modified while enumerating");
  338. yield return this.items[index].value;
  339. }
  340. }
  341. IEnumerator IEnumerable.GetEnumerator()
  342. {
  343. return GetEnumerator();
  344. }
  345. }
  346. }