File tree Expand file tree Collapse file tree 2 files changed +79
-0
lines changed
data-structures/binary-tree Expand file tree Collapse file tree 2 files changed +79
-0
lines changed Original file line number Diff line number Diff line change 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
Original file line number Diff line number Diff line change 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 )
You can’t perform that action at this time.
0 commit comments