1
0

MinHeap.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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.heap = null;
  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 = 16;
  88. items = new HeapItem[_capacity];
  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;
  166. int child;
  167. for(current = index , child = (2 * current) + 1;
  168. current < size / 2;
  169. current = child, child = (2 * current) + 1)
  170. {
  171. if ((child < size - 1) && comparison(items[child].value, items[child + 1].value) > 0)
  172. ++child;
  173. if (comparison(items[child].value, item.value) >= 0)
  174. break;
  175. Set(items[child], current);
  176. }
  177. if (current != index)
  178. {
  179. Set(item, current);
  180. ++version;
  181. }
  182. }
  183. public bool TryGetValue(IHandle key, out T value)
  184. {
  185. Handle handle = ValidateHandle(key);
  186. if (handle.index > -1)
  187. {
  188. value = items[handle.index].value;
  189. return true;
  190. }
  191. value = default(T);
  192. return false;
  193. }
  194. public bool ContainsHandle(IHandle ihandle)
  195. {
  196. Handle handle = ValidateHandle(ihandle);
  197. return object.ReferenceEquals(handle.heap, this) && handle.index > -1;
  198. }
  199. public void Add(T value, ref IHandle handle)
  200. {
  201. if (handle == null)
  202. handle = new Handle();
  203. Add(value, handle);
  204. }
  205. public void Add(T value, IHandle ihandle)
  206. {
  207. if (size == items.Length)
  208. {
  209. int newcapacity = (int)((items.Length * 200L) / 100L);
  210. if (newcapacity < (items.Length + DEFAULT_CAPACITY))
  211. newcapacity = items.Length + DEFAULT_CAPACITY;
  212. Array.Resize<HeapItem>(ref items, newcapacity);
  213. }
  214. Handle handle = null;
  215. if (ihandle != null)
  216. {
  217. handle = ValidateHandle(ihandle);
  218. handle.heap = this;
  219. }
  220. HeapItem item = new MinHeap<T>.HeapItem(value, handle);
  221. Set(item, size);
  222. BubbleUp(size++);
  223. }
  224. public void Add(T value)
  225. {
  226. Add(value, null);
  227. }
  228. public T Min()
  229. {
  230. if (size == 0)
  231. throw new InvalidOperationException("Heap is empty");
  232. return items[0].value;
  233. }
  234. public void Clear()
  235. {
  236. for (int index = 0; index < size; ++index)
  237. items[index].Clear();
  238. size = 0;
  239. if(items.Length > minCapacity)
  240. items = new HeapItem[minCapacity];
  241. ++version;
  242. }
  243. public void TrimExcess()
  244. {
  245. int length = (int)(items.Length * 0.9);
  246. if (size < length)
  247. Array.Resize<HeapItem>(ref items, Math.Min(size, minCapacity));
  248. }
  249. private void RemoveAt(int index)
  250. {
  251. if (size == 0)
  252. throw new InvalidOperationException("Heap is empty");
  253. if (index >= size)
  254. throw new ArgumentOutOfRangeException("index");
  255. items[index].Clear();
  256. --size;
  257. if (size > 0)
  258. { if(index != size)
  259. {
  260. Set(items[size], index);
  261. items[size].ClearRef();
  262. if (!BubbleUp(index))
  263. BubbleDown(index);
  264. }
  265. }
  266. else if(items.Length > 4 * minCapacity)
  267. items = new HeapItem[minCapacity];
  268. }
  269. public T RemoveMin()
  270. {
  271. if (size == 0)
  272. throw new InvalidOperationException("Heap is empty");
  273. HeapItem item = items[0];
  274. RemoveAt(0);
  275. return item.value;
  276. }
  277. public T Remove(IHandle ihandle)
  278. {
  279. Handle handle = ValidateThisHandle(ihandle);
  280. HeapItem item = items[handle.index];
  281. RemoveAt(handle.index);
  282. return item.value;
  283. }
  284. private int GetIndex(T value)
  285. {
  286. EqualityComparer<T> comparer = EqualityComparer<T>.Default;
  287. int index;
  288. for (index = 0; index < size; ++index)
  289. {
  290. if (comparer.Equals(items[index].value, value))
  291. return index;
  292. }
  293. return -1;
  294. }
  295. public bool Contains(T value)
  296. {
  297. return GetIndex(value) != -1;
  298. }
  299. public bool Remove(T value)
  300. {
  301. int index = GetIndex(value);
  302. if (index != -1)
  303. {
  304. RemoveAt(index);
  305. return true;
  306. }
  307. return false;
  308. }
  309. public void CopyTo(T[] array, int index)
  310. {
  311. if (array == null)
  312. throw new ArgumentNullException("array");
  313. if (array.Rank != 1)
  314. throw new ArgumentException("Multidimensional array not supported");
  315. if (array.GetLowerBound(0) != 0)
  316. throw new ArgumentException("Non-zero lower bound array not supported");
  317. int length = array.Length;
  318. if ((index < 0) || (index > length))
  319. throw new ArgumentOutOfRangeException("index");
  320. if ((length - index) < this.size)
  321. throw new ArgumentException("Not enough space available in array starting at index");
  322. for (int i = 0; i < size; ++i)
  323. array[index + i] = items[i].value;
  324. }
  325. public void CopyTo(Array array, int index)
  326. {
  327. if (array == null)
  328. throw new ArgumentNullException("array");
  329. if (array.Rank != 1)
  330. throw new ArgumentException("Multidimensional array not supported");
  331. if (array.GetLowerBound(0) != 0)
  332. throw new ArgumentException("Non-zero lower bound array not supported");
  333. int length = array.Length;
  334. if ((index < 0) || (index > length))
  335. throw new ArgumentOutOfRangeException("index");
  336. if ((length - index) < size)
  337. throw new ArgumentException("Not enough space available in array starting at index");
  338. try
  339. {
  340. for (int i = 0; i < size; ++i)
  341. array.SetValue(items[i].value, index + i);
  342. }
  343. catch (ArrayTypeMismatchException)
  344. {
  345. throw new ArgumentException("Invalid array type");
  346. }
  347. }
  348. public IEnumerator<T> GetEnumerator()
  349. {
  350. int cversion = version;
  351. for (int index = 0; index < size; ++index)
  352. {
  353. if (cversion != version)
  354. throw new InvalidOperationException("Heap was modified while enumerating");
  355. yield return items[index].value;
  356. }
  357. }
  358. IEnumerator IEnumerable.GetEnumerator()
  359. {
  360. return GetEnumerator();
  361. }
  362. }
  363. }