Created
March 29, 2021 00:17
-
-
Save savoygu/fb539b13b33e183594292c29ced3868d 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 = (x, y) => x > y) { | |
this.data = [] | |
this.comparator = comparator | |
} | |
insert(val) { | |
const data = this.data | |
data.push(val) | |
let index = data.length - 1 | |
while(index) { | |
const parent = Math.floor((index - 1) / 2) | |
if (!this.comparator(data[index], data[parent])) return; | |
this.swap(index, parent) | |
index = parent | |
} | |
} | |
extract() { | |
const data = this.data | |
this.swap(0, data.length - 1) | |
const val = data.pop() | |
const length = data.length | |
let index = 0, exchange = 2 * index + 1 | |
while(exchange < length) { | |
const right = exchange + 1 | |
if (right < length && this.comparator(data[right], data[exchange])) { | |
exchange = right | |
} | |
if (!this.comparator(data[exchange], data[index])) break | |
this.swap(index, exchange) | |
index = exchange | |
exchange = 2 * index + 1 | |
} | |
return val | |
} | |
top() { | |
return this.data.length > 0 ? this.data[0] : null | |
} | |
swap(i, j) { | |
const data = this.data; | |
[data[i], data[j]] = [data[j], data[i]] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment