Last active
January 5, 2026 01:04
-
-
Save DAB0mB/f9dcb41673584db2180b5e55611bd3bd to your computer and use it in GitHub Desktop.
Generic heap implementation
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 Heap<T> { | |
| constructor( | |
| private readonly compare: (a: T, b: T) => number, | |
| private readonly values: T[] = [], | |
| ) { | |
| this.values = values = values.slice(); | |
| if (values.length <= 1) return; | |
| for (let index = getParent(this.values.length - 1); index >= 0; index--) { | |
| this.sink(index); | |
| } | |
| } | |
| get size() { | |
| return this.values.length; | |
| } | |
| get head() { | |
| return this.values[0]; | |
| } | |
| push(value: T) { | |
| const length = this.values.push(value); | |
| if (length === 1) return; | |
| this.bubble(length - 1); | |
| return length; | |
| } | |
| pop() { | |
| if (this.values.length < 1) return; | |
| const value = this.values.pop()!; | |
| if (this.values.length === 0) return value; | |
| const head = this.values[0]; | |
| this.values[0] = value; | |
| if (this.values.length === 1) return head; | |
| this.sink(0); | |
| return head; | |
| } | |
| private bubble(index: number) { | |
| while (true) { | |
| let parent = getParent(index); | |
| if (parent === -1) break; | |
| if (this.compare(this.values[index], this.values[parent]) >= 0) break; | |
| [this.values[parent], this.values[index]] = [this.values[index], this.values[parent]]; | |
| index = parent; | |
| } | |
| } | |
| private sink(index: number) { | |
| while (true) { | |
| let left = getLeft(index); | |
| let right = getRight(index); | |
| let child = ( | |
| this.values.length <= left ? -1 : | |
| this.values.length <= right ? left : | |
| this.compare(this.values[right], this.values[left]) > 0 ? left : | |
| right | |
| ); | |
| if (child === -1) break; | |
| if (this.compare(this.values[child], this.values[index]) >= 0) break; | |
| [this.values[index], this.values[child]] = [this.values[child], this.values[index]]; | |
| index = child; | |
| } | |
| } | |
| } | |
| function getLeft(index: number) { | |
| return index * 2 + 1; | |
| } | |
| function getRight(index: number) { | |
| return index * 2 + 2; | |
| } | |
| function getParent(index: number) { | |
| return Math.floor((index - 1) / 2); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment