如下图所示:使用数组来表示二叉树,可得
const parent = i => (i-1) >>> 1;
const left = i => 1 + (i << 1);
const right = i => 2 + (i << 1);
const parent = i => (i-1) >>> 1;
const left = i => 1 + (i << 1);
const right = i => 2 + (i << 1);
const swap = (nums, l, r) => [nums[l], nums[r]]=[nums[r], nums[l]];
function toBottom(d, i, len, comp) {
while (i < len) {
let l = left(i), r = right(i), m = i;
if (l < len && comp(d[l], d[m]) <= 0) {
m = l;
}
if (r < len && comp(d[r], d[m]) <= 0) {
m = r;
}
if (m===i) break;
swap(d, i, m);
i = m;
}
}
function toUpper(d, i, comp) {
while (i) {
let p = parent(i);
if (comp(d[p], d[i]) <= 0) break;
swap(d, p, i);
i = p;
}
}
export class Heap {
constructor(comp = (a, b) => a - b) {
this.data = [];
this.comp = comp;
}
push(d) {
this.data.push(d);
toUpper(this.data, this.data.length - 1, this.comp);
}
peek() {
return this.data[0];
}
isEmpty() {
return this.data.length === 0;
}
pop() {
if (this.data.length <= 1) {
return this.data.pop();
}
const r = this.data[0];
this.data[0] = this.data.pop();
toBottom(this.data, 0, this.data.length - 1, this.comp);
return r;
}
static sort(arr, comp) {
for (let i = (arr.length >>> 1); i >= 0; i--) {
toBottom(arr, i, arr.length, comp);
}
for (let i = arr.length - 1; i > 0; i--) {
swap(arr, i, 0);
toBottom(arr, 0, i, comp);
}
arr.reverse();
}
}