Skip to content

Commit 1256bd4

Browse files
committed
docs(binary-tree): add binary heap implementation
1 parent 755324a commit 1256bd4

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
const Sort = require("../../algorithms/sorting/Sort")
2+
3+
class BinaryHeap extends Sort {
4+
#itemsCount
5+
#items
6+
7+
constructor() {
8+
super()
9+
10+
this.#items = []
11+
this.#itemsCount = 0
12+
}
13+
14+
insert(item) {
15+
this.#itemsCount++
16+
17+
this.#items[this.#itemsCount] = item
18+
19+
this.swimBinaryTreeNodes(this.#items, this.#itemsCount)
20+
}
21+
22+
delMax() {
23+
const isEmpty = this.isEmpty()
24+
25+
if (isEmpty) {
26+
throw new Error("This BinaryHeap is empty!")
27+
}
28+
29+
const maxItem = this.#items[1]
30+
31+
this.exchangeValues(this.#items, 1, this.#itemsCount)
32+
33+
delete this.#items[this.#itemsCount]
34+
35+
this.#itemsCount--
36+
37+
this.swimBinaryTreeNodes(this.#items, this.#itemsCount)
38+
39+
return maxItem
40+
}
41+
42+
size() {
43+
const size = this.#itemsCount
44+
45+
return size
46+
}
47+
48+
isEmpty() {
49+
const isEmpty = this.#itemsCount === 0
50+
51+
return isEmpty
52+
}
53+
54+
*[Symbol.iterator]() {
55+
for(let i = 0; i < this.size(); i++) {
56+
const item = this.pop()
57+
58+
yield item
59+
}
60+
}
61+
}
62+
63+
module.exports = BinaryHeap
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
const assert = require("assert")
2+
const BinaryHeap = require("./BinaryHeap.js")
3+
4+
const binaryHeap = new BinaryHeap()
5+
6+
binaryHeap.insert(3)
7+
binaryHeap.insert(2)
8+
binaryHeap.insert(5)
9+
10+
assert.deepEqual(binaryHeap.isEmpty(), false)
11+
assert.deepEqual(binaryHeap.size(), 3)
12+
assert.deepEqual(binaryHeap.delMax(), 5)
13+
assert.deepEqual(binaryHeap.delMax(), 3)
14+
assert.deepEqual(binaryHeap.delMax(), 2)
15+
assert.throws(() => binaryHeap.delMax())
16+
assert.deepEqual(binaryHeap.isEmpty(), true)

0 commit comments

Comments
 (0)