Created
December 30, 2019 03:22
-
-
Save dashsaurabh/7ab68fc2dcfcefe0e8c8e1c5b2eafcfa to your computer and use it in GitHub Desktop.
Heap Implementation in Javascript
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 MinBinaryHeap { | |
constructor() { | |
this.values = [] | |
} | |
insert(val) { | |
this.values.push(val) | |
//first element in the heap | |
if (this.values.length === 1) { | |
return true; | |
} | |
//bubble up the element to its right place in the heap | |
this.bubbleUpMin(); | |
} | |
extractMin() { | |
let lastElement = this.values.pop(); | |
if (this.values.length === 0) return lastElement; | |
let minElement = this.values[0]; | |
this.values[0] = lastElement; | |
//sink down the element to its right place in the heap | |
this.sinkDown(); | |
return minElement; | |
} | |
sinkDown() { | |
let index = 0; | |
let length = this.values.length; | |
let element = this.values[0]; | |
while(true) { | |
let leftChildIndex = index * 2 + 1; | |
let rightChildIndex = index * 2 + 1; | |
let leftChild, rightChild; | |
let swap = null; | |
//check if left child index is not out-of-bounds | |
if(leftChildIndex < length) { | |
leftChild = this.values[leftChildIndex]; | |
if(leftChild < element) { | |
swap = leftChildIndex; | |
} | |
} | |
//check if right child index is not out-of-bounds | |
if(rightChildIndex < length){ | |
rightChild = this.values[rightChildIndex]; | |
if( | |
(swap === null && rightChild < element) || | |
(swap !== null && rightChild < leftChild) | |
){ | |
swap = rightChildIndex | |
} | |
} | |
if (swap === null) break; | |
//swap the values | |
this.values[index] = this.values[swap]; | |
this.values[swap] = element; | |
index = swap; | |
} | |
} | |
bubbleUpMin() { | |
let index = this.values.length - 1 | |
let parentIndex, temp; | |
//loop till end of index | |
while(index > 0){ | |
parentIndex = Math.floor((index - 1) / 2) | |
if(this.values[index] >= this.values[parentIndex]) break; | |
temp = this.values[parentIndex]; | |
this.values[parentIndex] = this.values[index]; | |
this.values[index] = temp; | |
index = parentIndex; | |
} | |
} | |
} | |
let heap = new MinBinaryHeap(); | |
heap.insert(5); | |
heap.insert(8); | |
heap.insert(10); | |
heap.insert(4); | |
heap.extractMin(); | |
heap.extractMin(); | |
heap.extractMin(); | |
heap.extractMin(); | |
heap.extractMin(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment