-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_heap.js
66 lines (56 loc) · 1.75 KB
/
binary_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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* Binary Heap
*
* Construct a min-heap.
*/
function BinaryHeap(nums) {
this.arr = nums
this.size = nums.length
}
BinaryHeap.prototype.upAdjust = function() {
let childIndex = this.size - 1
let parentIndex = childIndex - 1 >> 1
const cacheChildValue = this.arr[childIndex]
while (parentIndex > -1 && cacheChildValue <= this.arr[parentIndex]) {
this.arr[childIndex] = this.arr[parentIndex]
childIndex = parentIndex
parentIndex = childIndex - 1 >> 1
}
this.arr[childIndex] = cacheChildValue
}
// Move big values down of the heap.
BinaryHeap.prototype.downAdjust = function(nodeIndex) {
const size = this.size
const arr = this.arr
let parentIndex = nodeIndex
const cacheParentValue = arr[parentIndex]
let childIndex = 2 * parentIndex + 1
while (childIndex < size) {
// Compare left child with right child
const rightChildIndex = childIndex + 1
if (rightChildIndex < size && arr[rightChildIndex] < arr[childIndex]) {
childIndex = rightChildIndex
}
if (cacheParentValue <= arr[childIndex]) { // The parent node has already been the smallest item compared to it's children
break
}
arr[parentIndex] = arr[childIndex]
parentIndex = childIndex
childIndex = 2 * parentIndex + 1
}
arr[parentIndex] = cacheParentValue
}
BinaryHeap.prototype.buildHeap = function() {
for (let i = this.size- 2 >> 1; i > -1; i--) {
this.downAdjust(i)
}
}
function main() {
const nums = [1, 19, 89, 23, 0, -111, 222, 99, 777, 3, 9, 45, 20, 8, 4, 921, 23, 17, 19, 23, 97, 59, 91, 100, 200, 300, 400, 545, -10000]
console.log('before: ', nums)
const binaryHeap = new BinaryHeap(nums)
binaryHeap.upAdjust()
// binaryHeap.buildHeap()
console.log('after heap built: ', nums, nums.length)
}
main()