-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathheap.js
49 lines (41 loc) · 1.04 KB
/
heap.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
(function(){
// Min Binary Heap
var Heap = function(){
var storage = [];
this.add = function(x){
storage.push(x);
var count = 0;
var childIndex = storage.length-1;
while(count<100 && childIndex>0){
count++;
var parentIndex = Math.floor((childIndex-1)/2);
if (storage[parentIndex]<storage[childIndex]){
var temp = storage[childIndex];
storage[childIndex] = storage[parentIndex];
storage[parentIndex] = temp;
childIndex = parentIndex;
} else {
break;
}
}
};
this.size = function(){ return storage.length;};
this.contains = function(x){
for (var i=0;i<storage.length;i++){
if (storage[i] === x ){
return true;
}
}
return false;
};
};
var root = this;
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = Heap;
}
exports.Heap = Heap;
} else {
root.Heap = Heap;
}
})();