Last active
March 12, 2020 02:39
-
-
Save Giagnus64/335680a89d5335873fc975fe3b8777c1 to your computer and use it in GitHub Desktop.
Binary Search Heap
This file contains hidden or 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 MaxBinaryHeap{ | |
| constructor(){ | |
| this.values = [] | |
| } | |
| //helper method that swaps the values and two indexes of an array | |
| swap(index1, index2){ | |
| let temp = this.values[index1]; | |
| this.values[index1] = this.values[index2]; | |
| this.values[index2] = temp; | |
| return this.values; | |
| } | |
| //helper methods that bubbles up values from end | |
| bubbleUp(){ | |
| //get index of inserted element | |
| let index = this.values.length - 1 | |
| //loop while index is not 0 or element no longer needs to bubble | |
| while(index > 0){ | |
| //get parent index via formula | |
| let parentIndex = Math.floor((index - 1)/2); | |
| //if values is greater than parent, swap the two | |
| if(this.values[parentIndex] < this.values[index]){ | |
| //swap with helper method | |
| this.swap(index, parentIndex); | |
| //change current index to parent index | |
| index = parentIndex; | |
| } else{ | |
| break; | |
| } | |
| } | |
| return 0; | |
| } | |
| // method that pushes new value onto the end and calls the bubble helper | |
| insert(value){ | |
| this.values.push(value) | |
| this.bubbleUp(); | |
| return this.values | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment