-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinaryheap.js
113 lines (102 loc) · 2.34 KB
/
binaryheap.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
"use strict";
/**
* Implementation of binaryHeap.
*
* @constructor
* @this {BinaryHeap}
* @param {number} _length The desired total length of the heap.
*/
class BinaryHeap {
constructor(_length) {
if (_length === undefined) _length = Infinity;
this.maxlenth = _length;
this.size = 0;
this.data = {};
}
/**
* Push a new value into the tree.
*
* @param {number} value The desired value to be added in the tree.
*/
push(value) {
this.size++;
let index = this.size - 1;
this.data[index] = value;
while (index != 0 && this.data[this.parent(index)] > this.data[index]) {
let temp = this.data[index];
this.data[index] = this.data[this.parent(index)];
this.data[this.parent(index)] = temp;
index = this.parent(index);
}
if (this.size > this.maxlenth) this.extractMin();
}
/**
* Remove and return the minimum element of the tree
*
*
*/
extractMin() {
if (this.size <= 0) return;
if (this.size === 1) {
this.size--;
return this.data[0];
}
let root = this.data[0];
this.data[0] = this.data[this.size - 1];
this.size--;
this.MinHeapify(0);
return root;
}
/**
* Re-order after removing the root of the tree
*
*
*/
MinHeapify(index) {
let left = this.left(index);
let right = this.right(index);
let smallest = index;
if (left < this.size && this.data[left] < this.data[index]) smallest = left;
if (right < this.size && this.data[right] < this.data[smallest])
smallest = right;
if (smallest != index) {
let temp = this.data[index];
this.data[index] = this.data[smallest];
this.data[smallest] = temp;
this.MinHeapify(smallest);
}
}
/**
* return the lowest element of the tree
*
*
*/
lower() {
return this.data[0];
}
/**
* compute the parent index of a node
*
* @param {number} index Index of the node.
*/
parent(index) {
return Math.floor((index - 1) / 2);
}
/**
* compute the left-leaf index of a node
*
* @param {number} index Index of the node.
*/
left(index) {
return Math.floor(2 * index + 1);
}
/**
* compute the right-leaf index of a node
*
* @param {number} index Index of the node.
*/
right(index) {
return Math.floor(2 * index + 2);
}
}
module.exports = BinaryHeap;