heap.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview Datastructure: Heap.
  16. *
  17. *
  18. * This file provides the implementation of a Heap datastructure. Smaller keys
  19. * rise to the top.
  20. *
  21. * The big-O notation for all operations are below:
  22. * <pre>
  23. * Method big-O
  24. * ----------------------------------------------------------------------------
  25. * - insert O(logn)
  26. * - remove O(logn)
  27. * - peek O(1)
  28. * - contains O(n)
  29. * </pre>
  30. */
  31. // TODO(user): Should this rely on natural ordering via some Comparable
  32. // interface?
  33. goog.provide('goog.structs.Heap');
  34. goog.require('goog.array');
  35. goog.require('goog.object');
  36. goog.require('goog.structs.Node');
  37. /**
  38. * Class for a Heap datastructure.
  39. *
  40. * @param {goog.structs.Heap|Object=} opt_heap Optional goog.structs.Heap or
  41. * Object to initialize heap with.
  42. * @constructor
  43. * @template K, V
  44. */
  45. goog.structs.Heap = function(opt_heap) {
  46. /**
  47. * The nodes of the heap.
  48. * @private
  49. * @type {Array<goog.structs.Node>}
  50. */
  51. this.nodes_ = [];
  52. if (opt_heap) {
  53. this.insertAll(opt_heap);
  54. }
  55. };
  56. /**
  57. * Insert the given value into the heap with the given key.
  58. * @param {K} key The key.
  59. * @param {V} value The value.
  60. */
  61. goog.structs.Heap.prototype.insert = function(key, value) {
  62. var node = new goog.structs.Node(key, value);
  63. var nodes = this.nodes_;
  64. nodes.push(node);
  65. this.moveUp_(nodes.length - 1);
  66. };
  67. /**
  68. * Adds multiple key-value pairs from another goog.structs.Heap or Object
  69. * @param {goog.structs.Heap|Object} heap Object containing the data to add.
  70. */
  71. goog.structs.Heap.prototype.insertAll = function(heap) {
  72. var keys, values;
  73. if (heap instanceof goog.structs.Heap) {
  74. keys = heap.getKeys();
  75. values = heap.getValues();
  76. // If it is a heap and the current heap is empty, I can rely on the fact
  77. // that the keys/values are in the correct order to put in the underlying
  78. // structure.
  79. if (this.getCount() <= 0) {
  80. var nodes = this.nodes_;
  81. for (var i = 0; i < keys.length; i++) {
  82. nodes.push(new goog.structs.Node(keys[i], values[i]));
  83. }
  84. return;
  85. }
  86. } else {
  87. keys = goog.object.getKeys(heap);
  88. values = goog.object.getValues(heap);
  89. }
  90. for (var i = 0; i < keys.length; i++) {
  91. this.insert(keys[i], values[i]);
  92. }
  93. };
  94. /**
  95. * Retrieves and removes the root value of this heap.
  96. * @return {V} The value removed from the root of the heap. Returns
  97. * undefined if the heap is empty.
  98. */
  99. goog.structs.Heap.prototype.remove = function() {
  100. var nodes = this.nodes_;
  101. var count = nodes.length;
  102. var rootNode = nodes[0];
  103. if (count <= 0) {
  104. return undefined;
  105. } else if (count == 1) {
  106. goog.array.clear(nodes);
  107. } else {
  108. nodes[0] = nodes.pop();
  109. this.moveDown_(0);
  110. }
  111. return rootNode.getValue();
  112. };
  113. /**
  114. * Retrieves but does not remove the root value of this heap.
  115. * @return {V} The value at the root of the heap. Returns
  116. * undefined if the heap is empty.
  117. */
  118. goog.structs.Heap.prototype.peek = function() {
  119. var nodes = this.nodes_;
  120. if (nodes.length == 0) {
  121. return undefined;
  122. }
  123. return nodes[0].getValue();
  124. };
  125. /**
  126. * Retrieves but does not remove the key of the root node of this heap.
  127. * @return {K} The key at the root of the heap. Returns undefined if the
  128. * heap is empty.
  129. */
  130. goog.structs.Heap.prototype.peekKey = function() {
  131. return this.nodes_[0] && this.nodes_[0].getKey();
  132. };
  133. /**
  134. * Moves the node at the given index down to its proper place in the heap.
  135. * @param {number} index The index of the node to move down.
  136. * @private
  137. */
  138. goog.structs.Heap.prototype.moveDown_ = function(index) {
  139. var nodes = this.nodes_;
  140. var count = nodes.length;
  141. // Save the node being moved down.
  142. var node = nodes[index];
  143. // While the current node has a child.
  144. while (index < (count >> 1)) {
  145. var leftChildIndex = this.getLeftChildIndex_(index);
  146. var rightChildIndex = this.getRightChildIndex_(index);
  147. // Determine the index of the smaller child.
  148. var smallerChildIndex = rightChildIndex < count &&
  149. nodes[rightChildIndex].getKey() < nodes[leftChildIndex].getKey() ?
  150. rightChildIndex :
  151. leftChildIndex;
  152. // If the node being moved down is smaller than its children, the node
  153. // has found the correct index it should be at.
  154. if (nodes[smallerChildIndex].getKey() > node.getKey()) {
  155. break;
  156. }
  157. // If not, then take the smaller child as the current node.
  158. nodes[index] = nodes[smallerChildIndex];
  159. index = smallerChildIndex;
  160. }
  161. nodes[index] = node;
  162. };
  163. /**
  164. * Moves the node at the given index up to its proper place in the heap.
  165. * @param {number} index The index of the node to move up.
  166. * @private
  167. */
  168. goog.structs.Heap.prototype.moveUp_ = function(index) {
  169. var nodes = this.nodes_;
  170. var node = nodes[index];
  171. // While the node being moved up is not at the root.
  172. while (index > 0) {
  173. // If the parent is less than the node being moved up, move the parent down.
  174. var parentIndex = this.getParentIndex_(index);
  175. if (nodes[parentIndex].getKey() > node.getKey()) {
  176. nodes[index] = nodes[parentIndex];
  177. index = parentIndex;
  178. } else {
  179. break;
  180. }
  181. }
  182. nodes[index] = node;
  183. };
  184. /**
  185. * Gets the index of the left child of the node at the given index.
  186. * @param {number} index The index of the node to get the left child for.
  187. * @return {number} The index of the left child.
  188. * @private
  189. */
  190. goog.structs.Heap.prototype.getLeftChildIndex_ = function(index) {
  191. return index * 2 + 1;
  192. };
  193. /**
  194. * Gets the index of the right child of the node at the given index.
  195. * @param {number} index The index of the node to get the right child for.
  196. * @return {number} The index of the right child.
  197. * @private
  198. */
  199. goog.structs.Heap.prototype.getRightChildIndex_ = function(index) {
  200. return index * 2 + 2;
  201. };
  202. /**
  203. * Gets the index of the parent of the node at the given index.
  204. * @param {number} index The index of the node to get the parent for.
  205. * @return {number} The index of the parent.
  206. * @private
  207. */
  208. goog.structs.Heap.prototype.getParentIndex_ = function(index) {
  209. return (index - 1) >> 1;
  210. };
  211. /**
  212. * Gets the values of the heap.
  213. * @return {!Array<V>} The values in the heap.
  214. */
  215. goog.structs.Heap.prototype.getValues = function() {
  216. var nodes = this.nodes_;
  217. var rv = [];
  218. var l = nodes.length;
  219. for (var i = 0; i < l; i++) {
  220. rv.push(nodes[i].getValue());
  221. }
  222. return rv;
  223. };
  224. /**
  225. * Gets the keys of the heap.
  226. * @return {!Array<K>} The keys in the heap.
  227. */
  228. goog.structs.Heap.prototype.getKeys = function() {
  229. var nodes = this.nodes_;
  230. var rv = [];
  231. var l = nodes.length;
  232. for (var i = 0; i < l; i++) {
  233. rv.push(nodes[i].getKey());
  234. }
  235. return rv;
  236. };
  237. /**
  238. * Whether the heap contains the given value.
  239. * @param {V} val The value to check for.
  240. * @return {boolean} Whether the heap contains the value.
  241. */
  242. goog.structs.Heap.prototype.containsValue = function(val) {
  243. return goog.array.some(
  244. this.nodes_, function(node) { return node.getValue() == val; });
  245. };
  246. /**
  247. * Whether the heap contains the given key.
  248. * @param {K} key The key to check for.
  249. * @return {boolean} Whether the heap contains the key.
  250. */
  251. goog.structs.Heap.prototype.containsKey = function(key) {
  252. return goog.array.some(
  253. this.nodes_, function(node) { return node.getKey() == key; });
  254. };
  255. /**
  256. * Clones a heap and returns a new heap
  257. * @return {!goog.structs.Heap} A new goog.structs.Heap with the same key-value
  258. * pairs.
  259. */
  260. goog.structs.Heap.prototype.clone = function() {
  261. return new goog.structs.Heap(this);
  262. };
  263. /**
  264. * The number of key-value pairs in the map
  265. * @return {number} The number of pairs.
  266. */
  267. goog.structs.Heap.prototype.getCount = function() {
  268. return this.nodes_.length;
  269. };
  270. /**
  271. * Returns true if this heap contains no elements.
  272. * @return {boolean} Whether this heap contains no elements.
  273. */
  274. goog.structs.Heap.prototype.isEmpty = function() {
  275. return goog.array.isEmpty(this.nodes_);
  276. };
  277. /**
  278. * Removes all elements from the heap.
  279. */
  280. goog.structs.Heap.prototype.clear = function() {
  281. goog.array.clear(this.nodes_);
  282. };