File tree Expand file tree Collapse file tree 1 file changed +85
-0
lines changed Expand file tree Collapse file tree 1 file changed +85
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Author: Samarth Jain
3
+ * Max Heap implementation in Javascript
4
+ */
5
+
6
+ class BinaryHeap {
7
+ constructor ( ) {
8
+ this . heap = [ ]
9
+ }
10
+
11
+ insert ( value ) {
12
+ this . heap . push ( value )
13
+ this . heapify ( )
14
+ }
15
+
16
+ size ( ) {
17
+ return this . heap . length
18
+ }
19
+
20
+ empty ( ) {
21
+ return this . size ( ) === 0
22
+ }
23
+
24
+ // using iterative approach to reorder the heap after insertion
25
+ heapify ( ) {
26
+ let index = this . size ( ) - 1
27
+
28
+ while ( index > 0 ) {
29
+ const element = this . heap [ index ]
30
+ const parentIndex = Math . floor ( ( index - 1 ) / 2 )
31
+ const parent = this . heap [ parentIndex ]
32
+
33
+ if ( parent [ 0 ] >= element [ 0 ] ) break
34
+ this . heap [ index ] = parent
35
+ this . heap [ parentIndex ] = element
36
+ index = parentIndex
37
+ }
38
+ }
39
+
40
+ // Extracting the maximum element from the Heap
41
+ extractMax ( ) {
42
+ const max = this . heap [ 0 ]
43
+ const tmp = this . heap . pop ( )
44
+ if ( ! this . empty ( ) ) {
45
+ this . heap [ 0 ] = tmp
46
+ this . sinkDown ( 0 )
47
+ }
48
+ return max
49
+ }
50
+
51
+ // To restore the balance of the heap after extraction.
52
+ sinkDown ( index ) {
53
+ const left = 2 * index + 1
54
+ const right = 2 * index + 2
55
+ let largest = index
56
+ const length = this . size ( )
57
+
58
+ if ( left < length && this . heap [ left ] [ 0 ] > this . heap [ largest ] [ 0 ] ) {
59
+ largest = left
60
+ }
61
+ if ( right < length && this . heap [ right ] [ 0 ] > this . heap [ largest ] [ 0 ] ) {
62
+ largest = right
63
+ }
64
+ // swap
65
+ if ( largest !== index ) {
66
+ const tmp = this . heap [ largest ]
67
+ this . heap [ largest ] = this . heap [ index ]
68
+ this . heap [ index ] = tmp
69
+ this . sinkDown ( largest )
70
+ }
71
+ }
72
+ }
73
+
74
+ const maxHeap = new BinaryHeap ( )
75
+ maxHeap . insert ( [ 4 ] )
76
+ maxHeap . insert ( [ 3 ] )
77
+ maxHeap . insert ( [ 6 ] )
78
+ maxHeap . insert ( [ 1 ] )
79
+ maxHeap . insert ( [ 8 ] )
80
+ maxHeap . insert ( [ 2 ] )
81
+
82
+ while ( ! maxHeap . empty ( ) ) {
83
+ const mx = maxHeap . extractMax ( )
84
+ console . log ( mx )
85
+ }
You can’t perform that action at this time.
0 commit comments