This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MinHeap { | |
constructor () { | |
/* Initialing the array heap and adding a dummy element at index 0 */ | |
this.heap = [null] | |
} | |
getMin () { | |
/* Accessing the min element at index 1 in the heap array */ | |
return this.heap[1] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
remove() { | |
/* Smallest element is at the index 1 in the heap array */ | |
let smallest = this.heap[1] | |
/* When there are more than two elements in the array, we put the right most element at the first position | |
and start comparing nodes with the child nodes | |
*/ | |
if (this.heap.length > 2) { | |
this.heap[1] = this.heap[this.heap.length-1] | |
this.heap.splice(this.heap.length - 1) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
insert (node) { | |
/* Inserting the new node at the end of the heap array */ | |
this.heap.push(node) | |
/* Finding the correct position for the new node */ | |
if (this.heap.length > 1) { | |
let current = this.heap.length - 1 | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MinHeap { | |
constructor () { | |
/* Initialing the array heap and adding a dummy element at index 0 */ | |
this.heap = [null] | |
} | |
getMin () { | |
/* Accessing the min element at index 1 in the heap array */ | |
return this.heap[1] |