MinHeap.cs 13 KB

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