1
0

MinHeap.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. if (this.handle != null)
  60. this.handle.Clear();
  61. ClearRef();
  62. }
  63. internal void ClearRef()
  64. {
  65. this.value = default(T);
  66. this.handle = null;
  67. }
  68. }
  69. public const int DEFAULT_CAPACITY = 4;
  70. private HeapItem[] items;
  71. private int size;
  72. private object sync_root;
  73. private int version;
  74. private Comparison<T> comparison;
  75. public MinHeap() : this(DEFAULT_CAPACITY, Comparer<T>.Default) { }
  76. public MinHeap(int capacity) : this(capacity, Comparer<T>.Default) { }
  77. public MinHeap(IComparer<T> comparer) : this(DEFAULT_CAPACITY, comparer) { }
  78. public MinHeap(int capacity, IComparer<T> comparer) :
  79. this(capacity, new Comparison<T>(comparer.Compare)) { }
  80. public MinHeap(Comparison<T> comparison) : this(DEFAULT_CAPACITY, comparison) { }
  81. public MinHeap(int capacity, Comparison<T> comparison)
  82. {
  83. this.items = new HeapItem[capacity];
  84. this.comparison = comparison;
  85. this.size = this.version = 0;
  86. }
  87. public int Count { get { return this.size; } }
  88. public bool IsReadOnly { get { return false; } }
  89. public bool IsSynchronized { get { return false; } }
  90. public T this[IHandle key]
  91. {
  92. get
  93. {
  94. Handle handle = ValidateThisHandle(key);
  95. return this.items[handle.index].value;
  96. }
  97. set
  98. {
  99. Handle handle = ValidateThisHandle(key);
  100. this.items[handle.index].value = value;
  101. if (!BubbleUp(handle.index))
  102. BubbleDown(handle.index);
  103. }
  104. }
  105. public object SyncRoot
  106. {
  107. get
  108. {
  109. if (this.sync_root == null)
  110. Interlocked.CompareExchange<object>(ref this.sync_root, new object(), null);
  111. return this.sync_root;
  112. }
  113. }
  114. private Handle ValidateHandle(IHandle ihandle)
  115. {
  116. if (ihandle == null)
  117. throw new ArgumentNullException("handle");
  118. Handle handle = ihandle as Handle;
  119. if (handle == null)
  120. throw new InvalidOperationException("handle is not valid");
  121. return handle;
  122. }
  123. private Handle ValidateThisHandle(IHandle ihandle)
  124. {
  125. Handle handle = ValidateHandle(ihandle);
  126. if (!object.ReferenceEquals(handle.heap, this))
  127. throw new InvalidOperationException("handle is not valid for this heap");
  128. if (handle.index < 0)
  129. throw new InvalidOperationException("handle is not associated to a value");
  130. return handle;
  131. }
  132. private void Set(HeapItem item, int index)
  133. {
  134. this.items[index] = item;
  135. if (item.handle != null)
  136. item.handle.index = index;
  137. }
  138. private bool BubbleUp(int index)
  139. {
  140. HeapItem item = this.items[index];
  141. int current, parent;
  142. for (current = index, parent = (current - 1) / 2;
  143. (current > 0) && (this.comparison(this.items[parent].value, item.value)) > 0;
  144. current = parent, parent = (current - 1) / 2)
  145. {
  146. Set(this.items[parent], current);
  147. }
  148. if (current != index)
  149. {
  150. Set(item, current);
  151. ++this.version;
  152. return true;
  153. }
  154. return false;
  155. }
  156. private void BubbleDown(int index)
  157. {
  158. HeapItem item = this.items[index];
  159. int current, child;
  160. for (current = index, child = (2 * current) + 1;
  161. current < this.size / 2;
  162. current = child, child = (2 * current) + 1)
  163. {
  164. if ((child < this.size - 1) && this.comparison(this.items[child].value, this.items[child + 1].value) > 0)
  165. ++child;
  166. if (this.comparison(this.items[child].value, item.value) >= 0)
  167. break;
  168. Set(this.items[child], current);
  169. }
  170. if (current != index)
  171. {
  172. Set(item, current);
  173. ++this.version;
  174. }
  175. }
  176. public bool TryGetValue(IHandle key, out T value)
  177. {
  178. Handle handle = ValidateHandle(key);
  179. if (handle.index > -1)
  180. {
  181. value = this.items[handle.index].value;
  182. return true;
  183. }
  184. value = default(T);
  185. return false;
  186. }
  187. public bool ContainsHandle(IHandle ihandle)
  188. {
  189. Handle handle = ValidateHandle(ihandle);
  190. return object.ReferenceEquals(handle.heap, this) && handle.index > -1;
  191. }
  192. public void Add(T value, ref IHandle handle)
  193. {
  194. if (handle == null)
  195. handle = new Handle();
  196. Add(value, handle);
  197. }
  198. public void Add(T value, IHandle ihandle)
  199. {
  200. if (this.size == this.items.Length)
  201. {
  202. int capacity = (int)((this.items.Length * 200L) / 100L);
  203. if (capacity < (this.items.Length + DEFAULT_CAPACITY))
  204. capacity = this.items.Length + DEFAULT_CAPACITY;
  205. Array.Resize<HeapItem>(ref this.items, capacity);
  206. }
  207. Handle handle = null;
  208. if (ihandle != null)
  209. {
  210. handle = ValidateHandle(ihandle);
  211. handle.heap = this;
  212. }
  213. HeapItem item = new MinHeap<T>.HeapItem(value, handle);
  214. Set(item, this.size);
  215. BubbleUp(this.size++);
  216. }
  217. public void Add(T value)
  218. {
  219. Add(value, null);
  220. }
  221. public T Min()
  222. {
  223. if (this.size == 0)
  224. throw new InvalidOperationException("Heap is empty");
  225. return this.items[0].value;
  226. }
  227. public void Clear()
  228. {
  229. for (int index = 0; index < this.size; ++index)
  230. this.items[index].Clear();
  231. this.size = 0;
  232. ++this.version;
  233. }
  234. public void TrimExcess()
  235. {
  236. int length = (int)(this.items.Length * 0.9);
  237. if (this.size < length)
  238. Array.Resize<HeapItem>(ref this.items, Math.Min(this.size, DEFAULT_CAPACITY));
  239. }
  240. private void RemoveAt(int index)
  241. {
  242. if (this.size == 0)
  243. throw new InvalidOperationException("Heap is empty");
  244. if (index >= this.size)
  245. throw new ArgumentOutOfRangeException("index");
  246. this.items[index].Clear();
  247. if (--this.size > 0 && index != this.size)
  248. {
  249. Set(this.items[this.size], index);
  250. this.items[this.size].ClearRef();
  251. if (!BubbleUp(index))
  252. BubbleDown(index);
  253. }
  254. }
  255. public T RemoveMin()
  256. {
  257. if (this.size == 0)
  258. throw new InvalidOperationException("Heap is empty");
  259. HeapItem item = this.items[0];
  260. RemoveAt(0);
  261. return item.value;
  262. }
  263. public T Remove(IHandle ihandle)
  264. {
  265. Handle handle = ValidateThisHandle(ihandle);
  266. HeapItem item = this.items[handle.index];
  267. RemoveAt(handle.index);
  268. return item.value;
  269. }
  270. private int GetIndex(T value)
  271. {
  272. EqualityComparer<T> comparer = EqualityComparer<T>.Default;
  273. int index;
  274. for (index = 0; index < this.size; ++index)
  275. {
  276. if (comparer.Equals(this.items[index].value, value))
  277. return index;
  278. }
  279. return -1;
  280. }
  281. public bool Contains(T value)
  282. {
  283. return GetIndex(value) != -1;
  284. }
  285. public bool Remove(T value)
  286. {
  287. int index = GetIndex(value);
  288. if (index != -1)
  289. {
  290. RemoveAt(index);
  291. return true;
  292. }
  293. return false;
  294. }
  295. public void CopyTo(T[] array, int index)
  296. {
  297. if (array == null)
  298. throw new ArgumentNullException("array");
  299. if (array.Rank != 1)
  300. throw new ArgumentException("Multidimensional array not supported");
  301. if (array.GetLowerBound(0) != 0)
  302. throw new ArgumentException("Non-zero lower bound array not supported");
  303. int length = array.Length;
  304. if ((index < 0) || (index > length))
  305. throw new ArgumentOutOfRangeException("index");
  306. if ((length - index) < this.size)
  307. throw new ArgumentException("Not enough space available in array starting at index");
  308. for (int i = 0; i < this.size; ++i)
  309. array[index + i] = this.items[i].value;
  310. }
  311. public void CopyTo(Array array, int index)
  312. {
  313. if (array == null)
  314. throw new ArgumentNullException("array");
  315. if (array.Rank != 1)
  316. throw new ArgumentException("Multidimensional array not supported");
  317. if (array.GetLowerBound(0) != 0)
  318. throw new ArgumentException("Non-zero lower bound array not supported");
  319. int length = array.Length;
  320. if ((index < 0) || (index > length))
  321. throw new ArgumentOutOfRangeException("index");
  322. if ((length - index) < this.size)
  323. throw new ArgumentException("Not enough space available in array starting at index");
  324. try
  325. {
  326. for (int i = 0; i < this.size; ++i)
  327. array.SetValue(this.items[i].value, index + i);
  328. }
  329. catch (ArrayTypeMismatchException)
  330. {
  331. throw new ArgumentException("Invalid array type");
  332. }
  333. }
  334. public IEnumerator<T> GetEnumerator()
  335. {
  336. int version = this.version;
  337. for (int index = 0; index < this.size; ++index)
  338. {
  339. if (version != this.version)
  340. throw new InvalidOperationException("Heap was modified while enumerating");
  341. yield return this.items[index].value;
  342. }
  343. }
  344. IEnumerator IEnumerable.GetEnumerator()
  345. {
  346. return GetEnumerator();
  347. }
  348. }
  349. }