Created
February 24, 2021 06:01
-
-
Save AlexJuarez/2f73877de1ca77c1c804a103bd28bf79 to your computer and use it in GitHub Desktop.
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 Heap { | |
constructor(comparator) { | |
this.arr = []; | |
this.compare = (i, j) => comparator(this.arr[i], this.arr[j]); | |
} | |
get size() { | |
return this.arr.length; | |
} | |
swap(a, b) { | |
const {arr} = this; | |
const temp = arr[a]; | |
arr[a] = arr[b]; | |
arr[b] = temp; | |
} | |
add(o) { | |
this.arr.push(o); | |
this.bubbleDown(this.size - 1); | |
} | |
bubbleDown(idx) { | |
if (idx === 0) { | |
return; | |
} | |
const parent = Math.floor(idx/2); | |
const res = this.compare(parent, idx); | |
if (res > 0) { | |
this.swap(idx, parent); | |
this.bubbleDown(parent); | |
} | |
} | |
remove() { | |
const {arr} = this; | |
if (!this.size) return null; | |
const first = arr[0]; | |
this.swap(0, this.size - 1); | |
this.arr.length--; | |
this.bubbleUp(); | |
return first; | |
} | |
bubbleUp(idx = 0) { | |
let children = []; | |
if (idx === 0) { | |
children.push(1); | |
} else{ | |
children.push(idx*2, idx*2+1); | |
} | |
children = children.filter(i => (i < this.size && this.compare(i, idx) < 0)); | |
if (children.length === 2) { | |
if (this.compare(children[0], children[1]) < 0) { | |
this.swap(children[0], idx) | |
this.bubbleUp(children[0]) | |
} else { | |
this.swap(children[1], idx) | |
this.bubbleUp(children[1]) | |
} | |
} else if (children.length === 1) { | |
if (this.compare(children[0], idx) < 0) { | |
this.swap(children[0], idx); | |
this.bubbleUp(children[0]); | |
} | |
} | |
} | |
} | |
const pq = new Heap((a, b) => b - a); | |
pq.add(3); | |
pq.add(4); | |
pq.add(2); | |
pq.add(1); | |
console.log(pq.remove(),pq.remove(),pq.remove(),pq.remove() ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment