Created
March 7, 2021 06:11
-
-
Save ibreathebsb/aa987e632c03f77986ec59c7087c9eec 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
function MinPQ() { | |
this.size = 0; | |
this.data = Array.from({ length: 10 }); | |
} | |
MinPQ.prototype.swap = function (i, j) { | |
const tmp = this.data[i]; | |
this.data[i] = this.data[j]; | |
this.data[j] = tmp; | |
} | |
MinPQ.prototype.up = function (k) { | |
while (k > 1 && this.data[Math.floor(k / 2)] > this.data[k]) { | |
this.swap(Math.floor(k / 2), k); | |
k = Math.floor(k / 2); | |
} | |
} | |
MinPQ.prototype.down = function (k) { | |
while (k <= this.size) { | |
if (2 * k + 1 <= this.size) { | |
// check both | |
const leftV = this.data[2 * k] | |
const rightV = this.data[2 * k + 1] | |
const minIndex = leftV < rightV ? 2 * k : 2 * k + 1; | |
const v = this.data[minIndex] | |
if (v < this.data[k]) { | |
this.swap(minIndex, k); | |
k = minIndex | |
} else { | |
break; | |
} | |
} else if (2 * k <= this.size) { | |
// check left | |
const leftV = this.data[2 * k] | |
if (leftV < this.data[k]) { | |
this.swap(2 * k, k) | |
k = 2 * k; | |
} else { | |
break; | |
} | |
} else { | |
break; | |
} | |
} | |
} | |
MinPQ.prototype.grow = function (v) { | |
const cap = this.data.length - 1; | |
const oldData = this.data; | |
const newCap = cap * 2 + 1; | |
const data = Array.from({ length: newCap }); | |
for (let i = 1; i <= this.size; i++) { | |
data[i] = oldData[i]; | |
} | |
this.data = data; | |
} | |
MinPQ.prototype.getCap = function () { | |
return this.data.length - 1; | |
} | |
MinPQ.prototype.insert = function (v) { | |
while (this.size >= this.getCap()) { | |
this.grow() | |
} | |
this.data[++this.size] = v; | |
this.up(this.size); | |
} | |
MinPQ.prototype.remove = function () { | |
if (this.size) { | |
const v = this.data[1]; | |
this.data[1] = this.data[this.size--]; | |
this.down(1); | |
return v; | |
} else { | |
return undefined; | |
} | |
} | |
MinPQ.prototype.isEmpty = function () { | |
return this.size === 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment