Skip to content

Instantly share code, notes, and snippets.

@KristopherGBaker
Last active December 14, 2023 16:49
Show Gist options
  • Save KristopherGBaker/ca4ac211de83c7ed99029eb04b5bd878 to your computer and use it in GitHub Desktop.
Save KristopherGBaker/ca4ac211de83c7ed99029eb04b5bd878 to your computer and use it in GitHub Desktop.
Simple Javascript Heap implementation
// usage:
// create a min heap
// const heap = new Heap((a, b) => a.val < b.val)
//
// create a max heap
// const heap = new Heap((a, b) => a.val > b.val)
//
// insert an item into the heap - O(lgn)
// heap.insert(item)
//
// check if the heap is empty - O(1)
// if (heap.isEmpty()) {...
//
// delete and retrieve the root element of the heap - O(lgn)
// let next = heap.delete()
class Heap {
#items
#comparator
constructor(comparator) {
this.#items = []
this.#comparator = comparator
}
count() {
return this.#items.length
}
isEmpty() {
return this.#items.length == 0
}
delete() {
if (this.isEmpty()) {
return null
}
const val = this.#items[0]
this.#items[0] = this.#items[this.#items.length - 1]
this.#items.pop()
if (!this.isEmpty()) {
this.#heapify(0)
}
return val
}
insert(value) {
this.#items.push(value)
this.#reverseHeapify(this.#items.length - 1)
}
#parent(index) {
const p = (index - 1) / 2
return Math.floor(p)
}
#left(index) {
return index * 2 + 1
}
#right(index) {
return index * 2 + 2
}
#reverseHeapify(index) {
if (index <= 0) {
return
}
const p = this.#parent(index)
if (this.#comparator(this.#items[index], this.#items[p])) {
this.#swap(p, index)
this.#reverseHeapify(p)
}
}
#swap(i, j) {
const tmp = this.#items[i]
this.#items[i] = this.#items[j]
this.#items[j] = tmp
}
#heapify(index) {
const l = this.#left(index)
const r = this.#right(index)
let smallest = index
if (l < this.#items.length && this.#comparator(this.#items[l], this.#items[index])) {
smallest = l
}
if (r < this.#items.length && this.#comparator(this.#items[r], this.#items[smallest])) {
smallest = r
}
if (smallest != index) {
this.#swap(smallest, index)
this.#heapify(smallest)
}
}
}
@rinogo
Copy link

rinogo commented Aug 10, 2022

I don't think this works.

const heap = new Heap((a, b) => a.val < b.val); //Min heap
heap.insert(5);
heap.insert(6);
heap.insert(4);
heap.insert(10);
heap.insert(1);
console.log(heap.delete());

...prints "5". Shouldn't it print "1"?

@monlovesmango
Copy link

you need to use comparator (a, b) => a < b
or insert items where they have the number stored in a val property

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment