Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9a53c98

Browse files
committed
Fix the liniting of the Heap
1 parent b5915b6 commit 9a53c98

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

src/data-structures/heap.js

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
(function (exports) {
2+
'use strict';
23

34
/**
45
* Constructor function of minimum heap
@@ -20,7 +21,8 @@
2021
/**
2122
* Exchange indexes with start index given as argument
2223
* to turn the tree into a valid heap. On a single call
23-
* this method maintains only a single "branch" of the heap. Complexity O(log n)
24+
* this method maintains only a single "branch" of the heap.
25+
* Complexity O(log n)
2426
*
2527
* @private
2628
* @param {number} index The parent
@@ -31,11 +33,15 @@
3133
right = 2 * index + 2,
3234
temp;
3335

34-
if (left < this._heap.length && this._cmp(this._heap[left], this._heap[index]) > 0)
36+
if (left < this._heap.length &&
37+
this._cmp(this._heap[left], this._heap[index]) > 0) {
3538
extr = left;
39+
}
3640

37-
if (right < this._heap.length && this._cmp(this._heap[right], this._heap[index]) > 0)
41+
if (right < this._heap.length &&
42+
this._cmp(this._heap[right], this._heap[index]) > 0) {
3843
extr = right;
44+
}
3945

4046
if (index !== extr) {
4147
temp = this._heap[index];
@@ -54,6 +60,7 @@
5460
* @returns {number} parent The new position of the element
5561
*/
5662
Heap.prototype.changeKey = function (index, value) {
63+
this._heap[index] = value;
5764
var elem = this._heap[index],
5865
parent = Math.floor(index / 2),
5966
temp;
@@ -92,21 +99,27 @@
9299
};
93100

94101
/**
95-
* Removes and returns the current extremum value which is on the top of the heap.
102+
* Removes and returns the current extremum value
103+
* which is on the top of the heap.
96104
* Complexity O(log n).
97105
*
98106
* @public
99107
* @returns {number} The extremum value
100108
*/
101109
Heap.prototype.extract = function () {
102-
if (!this._heap.length)
110+
if (!this._heap.length) {
103111
throw 'The heap is already empty!';
112+
}
104113

105114
var extr = this._heap.shift();
106115
this._heapify(0);
107116
return extr;
108117
};
109118

119+
Heap.prototype.getCollection = function () {
120+
return this._heap;
121+
};
122+
110123
Heap.prototype.isEmpty = function () {
111124
return !this._heap.length;
112125
};

0 commit comments

Comments
 (0)