-
Notifications
You must be signed in to change notification settings - Fork 71
/
binary-heaps-II.js
80 lines (60 loc) · 1.51 KB
/
binary-heaps-II.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
class Heap {
constructor() {
this.queue = []
}
push(val) {
this.queue.push(val)
this.sortWithFather(this.size())
}
size() {
return this.queue.length
}
pop() {
if (!this.size()) return null
const last = this.queue[this.queue.length - 1]
this.queue[this.queue.length - 1] = this.queue[0]
this.queue[0] = last
const result = this.queue.pop()
if (this.size() > 0) this.sortWithChildren(1)
return result
}
sortWithFather(cPos) {
let fPos = Math.floor(cPos / 2)
const target = this.queue[cPos - 1]
while (cPos > 1 && target < this.queue[fPos - 1]) {
this.queue[cPos - 1] = this.queue[fPos - 1]
cPos = fPos
fPos = Math.floor(cPos / 2)
}
this.queue[cPos - 1] = target
}
sortWithChildren(fPos) {
// 左子节点
let cPos = fPos * 2
const target = this.queue[fPos - 1]
while (cPos - 1 < this.queue.length) {
// 如果存在右子节点,且右子节点小于左子节点
if (cPos < this.queue.length && this.queue[cPos - 1] > this.queue[cPos]) {
cPos += 1
}
if (this.queue[cPos - 1] >= target) break
this.queue[fPos - 1] = this.queue[cPos - 1]
fPos = cPos
cPos = fPos * 2
}
this.queue[fPos - 1] = target
}
}
const heap = new Heap()
for (const num of [99, 1, 17, 0]) {
heap.push(num)
}
for (let i = 0; i < 4; i += 1) {
heap.push(
Math.floor(Math.random() * 100)
)
}
console.log(`[${heap.queue}]`)
while (heap.size()) {
console.log(heap.pop())
}