Last active
July 16, 2020 08:13
-
-
Save KristopherGBaker/0a3239b492d780d587d088f8ad192ec4 to your computer and use it in GitHub Desktop.
Alternative Javascript Heap implementation (works with CoderPad)
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
// 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 { | |
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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment