AI 代码审查:用 JavaScript min-max heap 实现双端优先队列

10-20 5阅读

让 AI 生成一个优先队列,常见答案是数组、交换函数和两段上浮下沉。可一旦需求变成“既能取出当前最小值,也能取出当前最大值”,把普通最小堆加上一个 max 方法就容易留下隐患:最大值可能藏在叶子,删除它又会破坏另一端的约束。看过几组正确输出,并不足以证明两端能够长期交替工作。

本文审查的是 min-max heap,也就是用一棵完全二叉树承载双端优先队列。重点不是按编号定位任务,也没有优先级更新、任意位置删除或句柄索引。我们只保存有限数值,提供 push、getMin、getMax、popMin、popMax 和 size。这个较窄的接口,足够把交替层、不等号、重复值和孙节点修复几个容易被 AI 混淆的问题讲清楚。

下文九段代码都可单独保存为 .cjs 文件,用 Node.js 执行。为便于复制复现,例子重复给出同一份完整类,不需要先运行前文,也不依赖第三方包。实际输出来自 Node.js v24.19.0,并用严格断言核对。配图只表达双端取值的概念,颜色和球体大小不承担算法语义。

AI 代码审查:用 JavaScript min-max heap 实现双端优先队列
AI概念图

一、先把数值多重集的接口写明白

双端优先队列中的“两端”是当前集合的最小优先级与最大优先级,不是插入顺序的头尾。重复数字必须作为独立条目保留:插入两次 2,就要删除两次才会消失。因此底层不能用 Set 替代数组,也不能拿数字本身当作唯一身份。本文不存任务对象,相同数值没有可观察的先后身份,也不承诺同优先级任务的稳定顺序。

空队列的四个读取或删除方法均返回 undefined,size 为零;push 遇到非有限 Number 时抛出 TypeError,并且先验证、后修改。负零统一转换为正零,省去数值排序以外的符号身份问题。Number.isFinite 不把字符串自动转换成数字,这与这里的严格输入合同一致,相关行为可核对 ECMAScript 规范。

下面先看完整实现和最小使用场景。私有数组只通过 snapshot 返回副本;它不是排序输出接口。例子最后显式排序,只为了把剩余多重集展示给读者,不参与堆的维护。get 方法不删除条目,而两个 pop 方法恰好删除一个条目。

"use strict";
class MinMaxHeap {
  #a = [];
  get size() { return this.#a.length; }
  snapshot() { return this.#a.slice(); }
  getMin() { return this.#a[0]; }
  getMax() { return this.#a[this.#maxIndex()]; }
  #maxIndex() {
    const a = this.#a;
    if (a.length === 0) return -1;
    if (a.length === 1) return 0;
    if (a.length === 2) return 1;
    return a[1] >= a[2] ? 1 : 2;
  }
  #minLevel(i) {
    let level = 0;
    for (let n = i + 1; n >= 2; n = Math.floor(n / 2)) level++;
    return level % 2 === 0;
  }
  #swap(i, j) { [this.#a[i], this.#a[j]] = [this.#a[j], this.#a[i]]; }
  #better(x, y, min) { return min ? x < y : x > y; }
  #up(i, min) {
    while (i >= 3) {
      const g = Math.floor((i - 3) / 4);
      if (!this.#better(this.#a[i], this.#a[g], min)) break;
      this.#swap(i, g);
      i = g;
    }
  }
  push(value) {
    if (!Number.isFinite(value)) throw new TypeError("finite number required");
    value = value === 0 ? 0 : value; // Normalize negative zero.
    const a = this.#a;
    let i = a.length;
    a.push(value);
    if (i === 0) return this;
    const p = Math.floor((i - 1) / 2);
    const min = this.#minLevel(i);
    if (this.#better(a[p], a[i], min)) {
      this.#swap(i, p);
      this.#up(p, !min);
    } else {
      this.#up(i, min);
    }
    return this;
  }
  #down(i, min) {
    const a = this.#a;
    for (;;) {
      let m = -1;
      const candidates = [2*i+1, 2*i+2, 4*i+3, 4*i+4, 4*i+5, 4*i+6];
      for (const k of candidates) {
        if (k < a.length && (m === -1 || this.#better(a[k], a[m], min))) m = k;
      }
      if (m === -1 || !this.#better(a[m], a[i], min)) return;
      const grandchild = m >= 4*i+3;
      this.#swap(i, m);
      if (!grandchild) return;
      const p = Math.floor((m - 1) / 2);
      if (this.#better(a[p], a[m], min)) this.#swap(m, p);
      i = m; // Continue from the same-parity grandchild slot.
    }
  }
  #remove(i) {
    if (i < 0 || this.size === 0) return undefined;
    const value = this.#a[i];
    const last = this.#a.pop();
    if (i < this.size) {
      this.#a[i] = last;
      this.#down(i, i === 0);
    }
    return value;
  }
  popMin() { return this.#remove(0); }
  popMax() { return this.#remove(this.#maxIndex()); }
}
const h = new MinMaxHeap();
for (const n of [7, 2, 9, 2, -4]) h.push(n);
console.log("ends:", h.getMin(), h.getMax(), "size:", h.size);
console.log("pop:", h.popMin(), h.popMax());
console.log("remaining:", JSON.stringify(h.snapshot().sort((a, b) => a - b)));

实际输出:

ends: -4 9 size: 5
pop: -4 9
remaining: [2,2,7]

二、交替层约束针对所有后代

数组使用零基下标。根在第零层,偶数层是 min 层,奇数层是 max 层。min 层节点必须不大于它的每一个后代,max 层节点必须不小于它的每一个后代。请注意“每一个后代”比“两个孩子”更强。只检查相邻父子边,可能漏掉隔了一层的反例。

这个定义以及沿同类层移动的思路来自 Atkinson 等人的原始论文。本文采用零基索引,并自行实现数值输入合同、私有状态和测试。下标 i 的孩子是 2i+1、2i+2,孙节点从 4i+3 到 4i+6;有祖父时,其下标是 floor((i-3)/4)。推导索引时要保持基准一致,不能把一基数组的公式直接贴过来。

实现用整数除法循环确定层的奇偶,避免把索引偷偷限制为位运算的有符号整数范围。测试则用另一条路径:对每个后代向上找全部祖先,按祖先层级检查关系。这样没有复用下沉时的六个候选位置生成器,能减少“算法与测试共用同一个错公式”的风险。

"use strict";
class MinMaxHeap {
  #a = [];
  get size() { return this.#a.length; }
  snapshot() { return this.#a.slice(); }
  getMin() { return this.#a[0]; }
  getMax() { return this.#a[this.#maxIndex()]; }
  #maxIndex() {
    const a = this.#a;
    if (a.length === 0) return -1;
    if (a.length === 1) return 0;
    if (a.length === 2) return 1;
    return a[1] >= a[2] ? 1 : 2;
  }
  #minLevel(i) {
    let level = 0;
    for (let n = i + 1; n >= 2; n = Math.floor(n / 2)) level++;
    return level % 2 === 0;
  }
  #swap(i, j) { [this.#a[i], this.#a[j]] = [this.#a[j], this.#a[i]]; }
  #better(x, y, min) { return min ? x < y : x > y; }
  #up(i, min) {
    while (i >= 3) {
      const g = Math.floor((i - 3) / 4);
      if (!this.#better(this.#a[i], this.#a[g], min)) break;
      this.#swap(i, g);
      i = g;
    }
  }
  push(value) {
    if (!Number.isFinite(value)) throw new TypeError("finite number required");
    value = value === 0 ? 0 : value; // Normalize negative zero.
    const a = this.#a;
    let i = a.length;
    a.push(value);
    if (i === 0) return this;
    const p = Math.floor((i - 1) / 2);
    const min = this.#minLevel(i);
    if (this.#better(a[p], a[i], min)) {
      this.#swap(i, p);
      this.#up(p, !min);
    } else {
      this.#up(i, min);
    }
    return this;
  }
  #down(i, min) {
    const a = this.#a;
    for (;;) {
      let m = -1;
      const candidates = [2*i+1, 2*i+2, 4*i+3, 4*i+4, 4*i+5, 4*i+6];
      for (const k of candidates) {
        if (k < a.length && (m === -1 || this.#better(a[k], a[m], min))) m = k;
      }
      if (m === -1 || !this.#better(a[m], a[i], min)) return;
      const grandchild = m >= 4*i+3;
      this.#swap(i, m);
      if (!grandchild) return;
      const p = Math.floor((m - 1) / 2);
      if (this.#better(a[p], a[m], min)) this.#swap(m, p);
      i = m; // Continue from the same-parity grandchild slot.
    }
  }
  #remove(i) {
    if (i < 0 || this.size === 0) return undefined;
    const value = this.#a[i];
    const last = this.#a.pop();
    if (i < this.size) {
      this.#a[i] = last;
      this.#down(i, i === 0);
    }
    return value;
  }
  popMin() { return this.#remove(0); }
  popMax() { return this.#remove(this.#maxIndex()); }
}
const assert = require("node:assert/strict");
function audit(heap, expected) {
  const a = heap.snapshot();
  assert.deepEqual(a.slice().sort((x, y) => x - y), expected);
  assert.equal(heap.size, expected.length);
  assert.equal(heap.getMin(), expected[0]);
  assert.equal(heap.getMax(), expected.at(-1));
  for (let j = 1; j < a.length; j++) {
    let ancestor = j;
    while (ancestor > 0) {
      ancestor = Math.floor((ancestor - 1) / 2);
      const level = Math.floor(Math.log2(ancestor + 1));
      assert.ok(level % 2 === 0 ? a[ancestor] <= a[j] : a[ancestor] >= a[j]);
    }
  }
}
const h = new MinMaxHeap();
for (const n of [9, 6, 9, 10, 13, 17, 20]) h.push(n);
audit(h, [6, 9, 9, 10, 13, 17, 20]);
const layout = h.snapshot().map((value, i) => {
  const level = Math.floor(Math.log2(i + 1));
  return `${i}:${level % 2 === 0 ? "min" : "max"}=${value}`;
});
console.log(layout.join(" "));
console.log("all ancestor-descendant relations: OK");

实际输出:

0:min=6 1:max=13 2:max=20 3:min=9 4:min=10 5:min=9 6:min=17
all ancestor-descendant relations: OK

三、插入先决定走哪一种层

新值先放到完全二叉树的下一个叶子位置。如果它落在 min 层,却比父节点还大,就与父节点交换,并从父节点所在的 max 层继续向上;如果没有越过父节点边界,就沿 min 层的祖父链上浮。落在 max 层时把大小关系反过来。代码中的 better 接受 min 参数,把两种方向汇聚在同一套控制流程里。

这种复用只有在含义清晰时才有价值。push 中比较的是父值是否比新值更适合当前层:min 层看到父值更小,就说明新值应该跨到 max 层。上浮循环随后每次跨两层,方向保持不变,不能继续像普通二叉堆那样逐个比较父节点。根没有父节点,必须提前结束。

下面让新值连续越过已有范围,同时加入相同最大值。每次 push 后都检查完整多重集、两端结果与全部祖先约束。只在最终状态测试,会遗漏某次插入已经破坏结构、又被后续插入偶然修补的情况;逐步审计才与可随时调用 get 或 pop 的接口合同一致。

"use strict";
class MinMaxHeap {
  #a = [];
  get size() { return this.#a.length; }
  snapshot() { return this.#a.slice(); }
  getMin() { return this.#a[0]; }
  getMax() { return this.#a[this.#maxIndex()]; }
  #maxIndex() {
    const a = this.#a;
    if (a.length === 0) return -1;
    if (a.length === 1) return 0;
    if (a.length === 2) return 1;
    return a[1] >= a[2] ? 1 : 2;
  }
  #minLevel(i) {
    let level = 0;
    for (let n = i + 1; n >= 2; n = Math.floor(n / 2)) level++;
    return level % 2 === 0;
  }
  #swap(i, j) { [this.#a[i], this.#a[j]] = [this.#a[j], this.#a[i]]; }
  #better(x, y, min) { return min ? x < y : x > y; }
  #up(i, min) {
    while (i >= 3) {
      const g = Math.floor((i - 3) / 4);
      if (!this.#better(this.#a[i], this.#a[g], min)) break;
      this.#swap(i, g);
      i = g;
    }
  }
  push(value) {
    if (!Number.isFinite(value)) throw new TypeError("finite number required");
    value = value === 0 ? 0 : value; // Normalize negative zero.
    const a = this.#a;
    let i = a.length;
    a.push(value);
    if (i === 0) return this;
    const p = Math.floor((i - 1) / 2);
    const min = this.#minLevel(i);
    if (this.#better(a[p], a[i], min)) {
      this.#swap(i, p);
      this.#up(p, !min);
    } else {
      this.#up(i, min);
    }
    return this;
  }
  #down(i, min) {
    const a = this.#a;
    for (;;) {
      let m = -1;
      const candidates = [2*i+1, 2*i+2, 4*i+3, 4*i+4, 4*i+5, 4*i+6];
      for (const k of candidates) {
        if (k < a.length && (m === -1 || this.#better(a[k], a[m], min))) m = k;
      }
      if (m === -1 || !this.#better(a[m], a[i], min)) return;
      const grandchild = m >= 4*i+3;
      this.#swap(i, m);
      if (!grandchild) return;
      const p = Math.floor((m - 1) / 2);
      if (this.#better(a[p], a[m], min)) this.#swap(m, p);
      i = m; // Continue from the same-parity grandchild slot.
    }
  }
  #remove(i) {
    if (i < 0 || this.size === 0) return undefined;
    const value = this.#a[i];
    const last = this.#a.pop();
    if (i < this.size) {
      this.#a[i] = last;
      this.#down(i, i === 0);
    }
    return value;
  }
  popMin() { return this.#remove(0); }
  popMax() { return this.#remove(this.#maxIndex()); }
}
const assert = require("node:assert/strict");
function audit(heap, expected) {
  const a = heap.snapshot();
  assert.deepEqual(a.slice().sort((x, y) => x - y), expected);
  assert.equal(heap.size, expected.length);
  assert.equal(heap.getMin(), expected[0]);
  assert.equal(heap.getMax(), expected.at(-1));
  for (let j = 1; j < a.length; j++) {
    let ancestor = j;
    while (ancestor > 0) {
      ancestor = Math.floor((ancestor - 1) / 2);
      const level = Math.floor(Math.log2(ancestor + 1));
      assert.ok(level % 2 === 0 ? a[ancestor] <= a[j] : a[ancestor] >= a[j]);
    }
  }
}
const h = new MinMaxHeap(), model = [];
for (const n of [10, 20, 30, 40, -5, 100, -20, 100]) {
  h.push(n); model.push(n); model.sort((a, b) => a - b);
  audit(h, model);
  console.log(`push ${n}: min=${h.getMin()}, max=${h.getMax()}`);
}

实际输出:

push 10: min=10, max=10
push 20: min=10, max=20
push 30: min=10, max=30
push 40: min=10, max=40
push -5: min=-5, max=40
push 100: min=-5, max=100
push -20: min=-20, max=100
push 100: min=-20, max=100

四、最大值的位置需要区分零、一、二个元素

根是全局最小值。非根节点属于根的某个子树,而根的两个孩子处在 max 层,所以最大值位于这两个孩子之中。这不等于总能访问下标 1 和 2:空堆没有候选,单元素时最大值仍在根,双元素时只有下标 1。代码把这些边界集中到 maxIndex,getMax 与 popMax 共享这一位置选择。

删除时先记住返回值,再取走数组末尾,用末尾值填补空位。若被删除位置就是原来的末尾,就没有要修复的节点。否则,删除根从 min 层向下修复,删除根的孩子从 max 层向下修复。这里没有实现通用的任意位置删除,不能把这个只下沉的策略直接套到内部任意下标。

为什么这几个位置不需要额外上浮?根没有祖先;删除最大值时,补入的末尾值原本就在根之下,因此仍不小于根。更高处没有其他祖先需要修复。下面独立建立两个队列,分别把每组输入从两端删空,同时核对重复删除空堆不会增加长度或留下伪元素。

"use strict";
class MinMaxHeap {
  #a = [];
  get size() { return this.#a.length; }
  snapshot() { return this.#a.slice(); }
  getMin() { return this.#a[0]; }
  getMax() { return this.#a[this.#maxIndex()]; }
  #maxIndex() {
    const a = this.#a;
    if (a.length === 0) return -1;
    if (a.length === 1) return 0;
    if (a.length === 2) return 1;
    return a[1] >= a[2] ? 1 : 2;
  }
  #minLevel(i) {
    let level = 0;
    for (let n = i + 1; n >= 2; n = Math.floor(n / 2)) level++;
    return level % 2 === 0;
  }
  #swap(i, j) { [this.#a[i], this.#a[j]] = [this.#a[j], this.#a[i]]; }
  #better(x, y, min) { return min ? x < y : x > y; }
  #up(i, min) {
    while (i >= 3) {
      const g = Math.floor((i - 3) / 4);
      if (!this.#better(this.#a[i], this.#a[g], min)) break;
      this.#swap(i, g);
      i = g;
    }
  }
  push(value) {
    if (!Number.isFinite(value)) throw new TypeError("finite number required");
    value = value === 0 ? 0 : value; // Normalize negative zero.
    const a = this.#a;
    let i = a.length;
    a.push(value);
    if (i === 0) return this;
    const p = Math.floor((i - 1) / 2);
    const min = this.#minLevel(i);
    if (this.#better(a[p], a[i], min)) {
      this.#swap(i, p);
      this.#up(p, !min);
    } else {
      this.#up(i, min);
    }
    return this;
  }
  #down(i, min) {
    const a = this.#a;
    for (;;) {
      let m = -1;
      const candidates = [2*i+1, 2*i+2, 4*i+3, 4*i+4, 4*i+5, 4*i+6];
      for (const k of candidates) {
        if (k < a.length && (m === -1 || this.#better(a[k], a[m], min))) m = k;
      }
      if (m === -1 || !this.#better(a[m], a[i], min)) return;
      const grandchild = m >= 4*i+3;
      this.#swap(i, m);
      if (!grandchild) return;
      const p = Math.floor((m - 1) / 2);
      if (this.#better(a[p], a[m], min)) this.#swap(m, p);
      i = m; // Continue from the same-parity grandchild slot.
    }
  }
  #remove(i) {
    if (i < 0 || this.size === 0) return undefined;
    const value = this.#a[i];
    const last = this.#a.pop();
    if (i < this.size) {
      this.#a[i] = last;
      this.#down(i, i === 0);
    }
    return value;
  }
  popMin() { return this.#remove(0); }
  popMax() { return this.#remove(this.#maxIndex()); }
}
const assert = require("node:assert/strict");
for (const input of [[], [5], [5, 1], [5, 1, 9], [5, 9, 1]]) {
  const low = new MinMaxHeap(), high = new MinMaxHeap();
  input.forEach(n => { low.push(n); high.push(n); });
  const ascending = [], descending = [];
  while (low.size) ascending.push(low.popMin());
  while (high.size) descending.push(high.popMax());
  assert.deepEqual(ascending, input.slice().sort((a, b) => a - b));
  assert.deepEqual(descending, input.slice().sort((a, b) => b - a));
  assert.equal(low.popMin(), undefined);
  assert.equal(high.popMax(), undefined);
  console.log(JSON.stringify({ input, ascending, descending }));
}

实际输出:

{"input":[],"ascending":[],"descending":[]}
{"input":[5],"ascending":[5],"descending":[5]}
{"input":[5,1],"ascending":[1,5],"descending":[5,1]}
{"input":[5,1,9],"ascending":[1,5,9],"descending":[9,5,1]}
{"input":[5,9,1],"ascending":[1,5,9],"descending":[9,5,1]}

五、孙节点交换以后还要修复它的父节点

这是最容易漏掉的一步。下沉不是只从两个孩子里挑选,而是从现存的孩子和孙节点里选择当前方向的极值。如果最合适的是孩子,交换一次即可结束;如果选中孙节点,跨越两层交换后,原位置的值已经落到孙节点槽位,可能越过中间父节点的反向边界。

下面的插入序列形成数组 [6,13,20,9,10,9,17]。删除最小值 6 后,末尾的 17 填到根,根与下标 3 的 9 交换。此时根变为 9,但下标 3 上的 17 大于其 max 层父节点 13。若只继续处理更深层,就会把错误留在上方。正确做法再交换 17 与 13,使父节点保持不小于后代。

完成父节点修复后,继续从刚才的孙节点下标下沉,而不是跟着被移到父节点的那个值走。我们正在修复一条同奇偶层的路径;该槽位可能换成了父节点旧值,它仍可能需要与更深的后代比较。max 层的过程完全对称。例子中 broken 是故意删掉这一步产生的反例,用来说明只看当前 getMin 和 getMax 仍可能看不出内部损坏。

"use strict";
class MinMaxHeap {
  #a = [];
  get size() { return this.#a.length; }
  snapshot() { return this.#a.slice(); }
  getMin() { return this.#a[0]; }
  getMax() { return this.#a[this.#maxIndex()]; }
  #maxIndex() {
    const a = this.#a;
    if (a.length === 0) return -1;
    if (a.length === 1) return 0;
    if (a.length === 2) return 1;
    return a[1] >= a[2] ? 1 : 2;
  }
  #minLevel(i) {
    let level = 0;
    for (let n = i + 1; n >= 2; n = Math.floor(n / 2)) level++;
    return level % 2 === 0;
  }
  #swap(i, j) { [this.#a[i], this.#a[j]] = [this.#a[j], this.#a[i]]; }
  #better(x, y, min) { return min ? x < y : x > y; }
  #up(i, min) {
    while (i >= 3) {
      const g = Math.floor((i - 3) / 4);
      if (!this.#better(this.#a[i], this.#a[g], min)) break;
      this.#swap(i, g);
      i = g;
    }
  }
  push(value) {
    if (!Number.isFinite(value)) throw new TypeError("finite number required");
    value = value === 0 ? 0 : value; // Normalize negative zero.
    const a = this.#a;
    let i = a.length;
    a.push(value);
    if (i === 0) return this;
    const p = Math.floor((i - 1) / 2);
    const min = this.#minLevel(i);
    if (this.#better(a[p], a[i], min)) {
      this.#swap(i, p);
      this.#up(p, !min);
    } else {
      this.#up(i, min);
    }
    return this;
  }
  #down(i, min) {
    const a = this.#a;
    for (;;) {
      let m = -1;
      const candidates = [2*i+1, 2*i+2, 4*i+3, 4*i+4, 4*i+5, 4*i+6];
      for (const k of candidates) {
        if (k < a.length && (m === -1 || this.#better(a[k], a[m], min))) m = k;
      }
      if (m === -1 || !this.#better(a[m], a[i], min)) return;
      const grandchild = m >= 4*i+3;
      this.#swap(i, m);
      if (!grandchild) return;
      const p = Math.floor((m - 1) / 2);
      if (this.#better(a[p], a[m], min)) this.#swap(m, p);
      i = m; // Continue from the same-parity grandchild slot.
    }
  }
  #remove(i) {
    if (i < 0 || this.size === 0) return undefined;
    const value = this.#a[i];
    const last = this.#a.pop();
    if (i < this.size) {
      this.#a[i] = last;
      this.#down(i, i === 0);
    }
    return value;
  }
  popMin() { return this.#remove(0); }
  popMax() { return this.#remove(this.#maxIndex()); }
}
const assert = require("node:assert/strict");
function audit(heap, expected) {
  const a = heap.snapshot();
  assert.deepEqual(a.slice().sort((x, y) => x - y), expected);
  assert.equal(heap.size, expected.length);
  assert.equal(heap.getMin(), expected[0]);
  assert.equal(heap.getMax(), expected.at(-1));
  for (let j = 1; j < a.length; j++) {
    let ancestor = j;
    while (ancestor > 0) {
      ancestor = Math.floor((ancestor - 1) / 2);
      const level = Math.floor(Math.log2(ancestor + 1));
      assert.ok(level % 2 === 0 ? a[ancestor] <= a[j] : a[ancestor] >= a[j]);
    }
  }
}
const h = new MinMaxHeap();
[9, 6, 9, 10, 13, 17, 20].forEach(n => h.push(n));
console.log("before:", JSON.stringify(h.snapshot()));
assert.equal(h.popMin(), 6);
console.log("after:", JSON.stringify(h.snapshot()));
audit(h, [9, 9, 10, 13, 17, 20]);
// This is the state produced if the parent repair is omitted.
const broken = [9, 13, 20, 17, 10, 9];
assert.ok(broken[1] < broken[3]);
console.log(`missing repair: max-level 13 < descendant 17`);

实际输出:

before: [6,13,20,9,10,9,17]
after: [9,17,20,13,10,9]
missing repair: max-level 13 < descendant 17

六、重复优先级必须被当作数量

严格小于与严格大于是这里有意选择的停止条件。值相等时不用交换,因为不变量允许相等。为了“让堆更规整”而把判断改成小于等于,既没有给重复值增加意义,还会使本来能够直接停止的路径继续移动。更危险的修改是查重或去重,那会改变优先队列保存的条目数量。

第一组测试混合删除最大值和最小值,直到六个条目全部取出。第二组把十二个完全相同的数字交替从两端删除,每一步都核对剩余数量。这里不检查相同值曾位于哪个数组槽位,因为堆并不承诺内部布局稳定。断言应围绕公开合同,不该把一种偶然排列写成接口规范。

如果以后扩展为带任务对象的队列,必须另行决定相同优先级怎样排序。加入递增序号形成复合排序键,会让取最小端与取最大端对序号的偏好相反;这不自动等于“两端都先进先出”。本文把这一业务问题留在接口边界之外,不用数值例子的通过来替对象版本背书。

"use strict";
class MinMaxHeap {
  #a = [];
  get size() { return this.#a.length; }
  snapshot() { return this.#a.slice(); }
  getMin() { return this.#a[0]; }
  getMax() { return this.#a[this.#maxIndex()]; }
  #maxIndex() {
    const a = this.#a;
    if (a.length === 0) return -1;
    if (a.length === 1) return 0;
    if (a.length === 2) return 1;
    return a[1] >= a[2] ? 1 : 2;
  }
  #minLevel(i) {
    let level = 0;
    for (let n = i + 1; n >= 2; n = Math.floor(n / 2)) level++;
    return level % 2 === 0;
  }
  #swap(i, j) { [this.#a[i], this.#a[j]] = [this.#a[j], this.#a[i]]; }
  #better(x, y, min) { return min ? x < y : x > y; }
  #up(i, min) {
    while (i >= 3) {
      const g = Math.floor((i - 3) / 4);
      if (!this.#better(this.#a[i], this.#a[g], min)) break;
      this.#swap(i, g);
      i = g;
    }
  }
  push(value) {
    if (!Number.isFinite(value)) throw new TypeError("finite number required");
    value = value === 0 ? 0 : value; // Normalize negative zero.
    const a = this.#a;
    let i = a.length;
    a.push(value);
    if (i === 0) return this;
    const p = Math.floor((i - 1) / 2);
    const min = this.#minLevel(i);
    if (this.#better(a[p], a[i], min)) {
      this.#swap(i, p);
      this.#up(p, !min);
    } else {
      this.#up(i, min);
    }
    return this;
  }
  #down(i, min) {
    const a = this.#a;
    for (;;) {
      let m = -1;
      const candidates = [2*i+1, 2*i+2, 4*i+3, 4*i+4, 4*i+5, 4*i+6];
      for (const k of candidates) {
        if (k < a.length && (m === -1 || this.#better(a[k], a[m], min))) m = k;
      }
      if (m === -1 || !this.#better(a[m], a[i], min)) return;
      const grandchild = m >= 4*i+3;
      this.#swap(i, m);
      if (!grandchild) return;
      const p = Math.floor((m - 1) / 2);
      if (this.#better(a[p], a[m], min)) this.#swap(m, p);
      i = m; // Continue from the same-parity grandchild slot.
    }
  }
  #remove(i) {
    if (i < 0 || this.size === 0) return undefined;
    const value = this.#a[i];
    const last = this.#a.pop();
    if (i < this.size) {
      this.#a[i] = last;
      this.#down(i, i === 0);
    }
    return value;
  }
  popMin() { return this.#remove(0); }
  popMax() { return this.#remove(this.#maxIndex()); }
}
const assert = require("node:assert/strict");
function audit(heap, expected) {
  const a = heap.snapshot();
  assert.deepEqual(a.slice().sort((x, y) => x - y), expected);
  assert.equal(heap.size, expected.length);
  assert.equal(heap.getMin(), expected[0]);
  assert.equal(heap.getMax(), expected.at(-1));
  for (let j = 1; j < a.length; j++) {
    let ancestor = j;
    while (ancestor > 0) {
      ancestor = Math.floor((ancestor - 1) / 2);
      const level = Math.floor(Math.log2(ancestor + 1));
      assert.ok(level % 2 === 0 ? a[ancestor] <= a[j] : a[ancestor] >= a[j]);
    }
  }
}
const h = new MinMaxHeap();
[4, 4, 1, 4, 1, 4].forEach(n => h.push(n));
const removed = [h.popMax(), h.popMin(), h.popMax(), h.popMin(), h.popMin(), h.popMax()];
assert.deepEqual(removed, [4, 1, 4, 1, 4, 4]);
assert.equal(h.size, 0);
console.log("duplicates:", JSON.stringify(removed));
for (let i = 0; i < 12; i++) h.push(7);
for (let i = 0; i < 12; i++) {
  assert.equal(i % 2 ? h.popMax() : h.popMin(), 7);
  audit(h, Array(11 - i).fill(7));
}
console.log("all-equal mixed drain: 12 preserved");

实际输出:

duplicates: [4,1,4,1,4,4]
all-equal mixed drain: 12 preserved

七、用独立排序数组充当判定器

好的判定器应尽量避免与被测实现共享结构。这里的参考模型只是一份普通数组:插入时追加并排序,删除最小端用 shift,删除最大端用 pop。它不计算堆层、不查祖父,也不执行孙节点交换。生产堆与参考数组同时接收相同操作,然后逐步比较结果。

仅核对 pop 的返回值还不够。一次错误交换可能没有立即改变两端,却造成将来的失败;一次重复值丢失也可能被后续同值输出掩盖。因此 audit 同时核对 size、排序后的完整多重集、getMin、getMax 和全部祖先约束。两端 get 是读取操作,运行 audit 后也不应改变队列状态。

参考模型可以有较高维护成本,因为它的职责是提供简单、可解释的期望结果。不要为了让测试看起来“更像正式实现”,再写一个结构相似的双端堆。下面的操作序列还包含删空后的再次删除,明确把 undefined 与真实数字区分开;输出里的 empty 仅用于展示,队列本身仍返回 undefined。

"use strict";
class MinMaxHeap {
  #a = [];
  get size() { return this.#a.length; }
  snapshot() { return this.#a.slice(); }
  getMin() { return this.#a[0]; }
  getMax() { return this.#a[this.#maxIndex()]; }
  #maxIndex() {
    const a = this.#a;
    if (a.length === 0) return -1;
    if (a.length === 1) return 0;
    if (a.length === 2) return 1;
    return a[1] >= a[2] ? 1 : 2;
  }
  #minLevel(i) {
    let level = 0;
    for (let n = i + 1; n >= 2; n = Math.floor(n / 2)) level++;
    return level % 2 === 0;
  }
  #swap(i, j) { [this.#a[i], this.#a[j]] = [this.#a[j], this.#a[i]]; }
  #better(x, y, min) { return min ? x < y : x > y; }
  #up(i, min) {
    while (i >= 3) {
      const g = Math.floor((i - 3) / 4);
      if (!this.#better(this.#a[i], this.#a[g], min)) break;
      this.#swap(i, g);
      i = g;
    }
  }
  push(value) {
    if (!Number.isFinite(value)) throw new TypeError("finite number required");
    value = value === 0 ? 0 : value; // Normalize negative zero.
    const a = this.#a;
    let i = a.length;
    a.push(value);
    if (i === 0) return this;
    const p = Math.floor((i - 1) / 2);
    const min = this.#minLevel(i);
    if (this.#better(a[p], a[i], min)) {
      this.#swap(i, p);
      this.#up(p, !min);
    } else {
      this.#up(i, min);
    }
    return this;
  }
  #down(i, min) {
    const a = this.#a;
    for (;;) {
      let m = -1;
      const candidates = [2*i+1, 2*i+2, 4*i+3, 4*i+4, 4*i+5, 4*i+6];
      for (const k of candidates) {
        if (k < a.length && (m === -1 || this.#better(a[k], a[m], min))) m = k;
      }
      if (m === -1 || !this.#better(a[m], a[i], min)) return;
      const grandchild = m >= 4*i+3;
      this.#swap(i, m);
      if (!grandchild) return;
      const p = Math.floor((m - 1) / 2);
      if (this.#better(a[p], a[m], min)) this.#swap(m, p);
      i = m; // Continue from the same-parity grandchild slot.
    }
  }
  #remove(i) {
    if (i < 0 || this.size === 0) return undefined;
    const value = this.#a[i];
    const last = this.#a.pop();
    if (i < this.size) {
      this.#a[i] = last;
      this.#down(i, i === 0);
    }
    return value;
  }
  popMin() { return this.#remove(0); }
  popMax() { return this.#remove(this.#maxIndex()); }
}
const assert = require("node:assert/strict");
function audit(heap, expected) {
  const a = heap.snapshot();
  assert.deepEqual(a.slice().sort((x, y) => x - y), expected);
  assert.equal(heap.size, expected.length);
  assert.equal(heap.getMin(), expected[0]);
  assert.equal(heap.getMax(), expected.at(-1));
  for (let j = 1; j < a.length; j++) {
    let ancestor = j;
    while (ancestor > 0) {
      ancestor = Math.floor((ancestor - 1) / 2);
      const level = Math.floor(Math.log2(ancestor + 1));
      assert.ok(level % 2 === 0 ? a[ancestor] <= a[j] : a[ancestor] >= a[j]);
    }
  }
}
const ops = [8, 3, 3, "max", -2, 11, "min", 3, "min", "max", "max", "min", "min"];
const h = new MinMaxHeap(), sorted = [], popped = [];
for (const op of ops) {
  if (typeof op === "number") {
    h.push(op); sorted.push(op); sorted.sort((a, b) => a - b);
  } else {
    const actual = op === "min" ? h.popMin() : h.popMax();
    const expected = op === "min" ? sorted.shift() : sorted.pop();
    assert.equal(actual, expected);
    popped.push(actual === undefined ? "empty" : actual);
  }
  audit(h, sorted);
}
console.log("popped:", JSON.stringify(popped));
console.log("independent sorted-array oracle: OK");

实际输出:

popped: [8,-2,3,11,3,3,"empty"]
independent sorted-array oracle: OK

八、小状态空间穷举比几条随机样例更有解释力

固定随机种子有助于复现,但不能替代有边界的穷举。下面把操作字母表限制为插入 -1、0、1、删除最小值、删除最大值,枚举长度不超过六的所有操作序列。每一条序列都从空堆重放,保证错误上下文能够完整打印出来,不需要猜测之前发生了什么。

这个空间包含大量重复优先级、空队列删除,以及插入与两端删除的交错。序列数量为 19531,状态检查次数为 131836,包括每次重放的初始空状态。它们只是已验证覆盖范围的计数,不能证明所有长度、所有 JavaScript 数值都没有问题,也不是运行速度测量。

额外测试把混合序列上限提高到八,并遍历长度不超过六的三值输入及全部两端删空方式,再加入固定种子的较长操作历史。前者系统覆盖短路径,后者帮助触发更深的祖父链与反复下沉。审查 AI 代码时,这些证据应与不变量推理一起阅读;测试通过不能代替解释为什么父节点修复是必要的。

"use strict";
class MinMaxHeap {
  #a = [];
  get size() { return this.#a.length; }
  snapshot() { return this.#a.slice(); }
  getMin() { return this.#a[0]; }
  getMax() { return this.#a[this.#maxIndex()]; }
  #maxIndex() {
    const a = this.#a;
    if (a.length === 0) return -1;
    if (a.length === 1) return 0;
    if (a.length === 2) return 1;
    return a[1] >= a[2] ? 1 : 2;
  }
  #minLevel(i) {
    let level = 0;
    for (let n = i + 1; n >= 2; n = Math.floor(n / 2)) level++;
    return level % 2 === 0;
  }
  #swap(i, j) { [this.#a[i], this.#a[j]] = [this.#a[j], this.#a[i]]; }
  #better(x, y, min) { return min ? x < y : x > y; }
  #up(i, min) {
    while (i >= 3) {
      const g = Math.floor((i - 3) / 4);
      if (!this.#better(this.#a[i], this.#a[g], min)) break;
      this.#swap(i, g);
      i = g;
    }
  }
  push(value) {
    if (!Number.isFinite(value)) throw new TypeError("finite number required");
    value = value === 0 ? 0 : value; // Normalize negative zero.
    const a = this.#a;
    let i = a.length;
    a.push(value);
    if (i === 0) return this;
    const p = Math.floor((i - 1) / 2);
    const min = this.#minLevel(i);
    if (this.#better(a[p], a[i], min)) {
      this.#swap(i, p);
      this.#up(p, !min);
    } else {
      this.#up(i, min);
    }
    return this;
  }
  #down(i, min) {
    const a = this.#a;
    for (;;) {
      let m = -1;
      const candidates = [2*i+1, 2*i+2, 4*i+3, 4*i+4, 4*i+5, 4*i+6];
      for (const k of candidates) {
        if (k < a.length && (m === -1 || this.#better(a[k], a[m], min))) m = k;
      }
      if (m === -1 || !this.#better(a[m], a[i], min)) return;
      const grandchild = m >= 4*i+3;
      this.#swap(i, m);
      if (!grandchild) return;
      const p = Math.floor((m - 1) / 2);
      if (this.#better(a[p], a[m], min)) this.#swap(m, p);
      i = m; // Continue from the same-parity grandchild slot.
    }
  }
  #remove(i) {
    if (i < 0 || this.size === 0) return undefined;
    const value = this.#a[i];
    const last = this.#a.pop();
    if (i < this.size) {
      this.#a[i] = last;
      this.#down(i, i === 0);
    }
    return value;
  }
  popMin() { return this.#remove(0); }
  popMax() { return this.#remove(this.#maxIndex()); }
}
const assert = require("node:assert/strict");
function audit(heap, expected) {
  const a = heap.snapshot();
  assert.deepEqual(a.slice().sort((x, y) => x - y), expected);
  assert.equal(heap.size, expected.length);
  assert.equal(heap.getMin(), expected[0]);
  assert.equal(heap.getMax(), expected.at(-1));
  for (let j = 1; j < a.length; j++) {
    let ancestor = j;
    while (ancestor > 0) {
      ancestor = Math.floor((ancestor - 1) / 2);
      const level = Math.floor(Math.log2(ancestor + 1));
      assert.ok(level % 2 === 0 ? a[ancestor] <= a[j] : a[ancestor] >= a[j]);
    }
  }
}
const actions = [-1, 0, 1, "min", "max"];
let sequences = 0, states = 0;
function check(ops) {
  const h = new MinMaxHeap(), sorted = [];
  audit(h, sorted); states++;
  for (const op of ops) {
    if (typeof op === "number") {
      h.push(op); sorted.push(op); sorted.sort((a, b) => a - b);
    } else {
      assert.equal(op === "min" ? h.popMin() : h.popMax(),
                   op === "min" ? sorted.shift() : sorted.pop());
    }
    audit(h, sorted); states++;
  }
}
function visit(prefix, remaining) {
  check(prefix); sequences++;
  if (remaining === 0) return;
  for (const action of actions) visit(prefix.concat(action), remaining - 1);
}
visit([], 6);
console.log(JSON.stringify({ sequences, states }));

实际输出:

{"sequences":19531,"states":131836}

九、拒绝坏输入也要验证没有副作用

NaN 会使常见的大小比较同时返回 false,悄悄破坏排序前提,所以必须在写入数组之前拒绝。无穷大在某些设计里可以合法使用,但本文选择有限数值合同,统一拒绝它与负无穷大。字符串、BigInt 和包装数字对象同样不被接受。这样的限制不代表这些类型无法支持,而是避免比较规则在例子中发生隐式变化。

下面每次故意传入坏值前保存快照,异常后比较整个数组,防止出现“抛了异常但已塞入一半状态”的实现。另一个断言修改 snapshot 的结果,确认外部拿到的是副本。最后加入极大与极小有限值,堆的核心比较直接使用关系运算符,没有把两个优先级相减作为内部比较结果。

在数组下标访问与末尾增删按单位成本计的算法模型中,对 n 个条目,getMin、getMax 和 size 只查看固定数量的位置;push 与两端 pop 沿树高移动,渐近上界为 O(log n),存储为 O(n)。snapshot 会复制 n 个条目,测试里的排序和祖先检查也属于额外工作。本文通过逐个 push 构建队列,构建上界为 O(n log n),没有实现线性建堆,更没有据此声称某种实际运行速度优势。

"use strict";
class MinMaxHeap {
  #a = [];
  get size() { return this.#a.length; }
  snapshot() { return this.#a.slice(); }
  getMin() { return this.#a[0]; }
  getMax() { return this.#a[this.#maxIndex()]; }
  #maxIndex() {
    const a = this.#a;
    if (a.length === 0) return -1;
    if (a.length === 1) return 0;
    if (a.length === 2) return 1;
    return a[1] >= a[2] ? 1 : 2;
  }
  #minLevel(i) {
    let level = 0;
    for (let n = i + 1; n >= 2; n = Math.floor(n / 2)) level++;
    return level % 2 === 0;
  }
  #swap(i, j) { [this.#a[i], this.#a[j]] = [this.#a[j], this.#a[i]]; }
  #better(x, y, min) { return min ? x < y : x > y; }
  #up(i, min) {
    while (i >= 3) {
      const g = Math.floor((i - 3) / 4);
      if (!this.#better(this.#a[i], this.#a[g], min)) break;
      this.#swap(i, g);
      i = g;
    }
  }
  push(value) {
    if (!Number.isFinite(value)) throw new TypeError("finite number required");
    value = value === 0 ? 0 : value; // Normalize negative zero.
    const a = this.#a;
    let i = a.length;
    a.push(value);
    if (i === 0) return this;
    const p = Math.floor((i - 1) / 2);
    const min = this.#minLevel(i);
    if (this.#better(a[p], a[i], min)) {
      this.#swap(i, p);
      this.#up(p, !min);
    } else {
      this.#up(i, min);
    }
    return this;
  }
  #down(i, min) {
    const a = this.#a;
    for (;;) {
      let m = -1;
      const candidates = [2*i+1, 2*i+2, 4*i+3, 4*i+4, 4*i+5, 4*i+6];
      for (const k of candidates) {
        if (k < a.length && (m === -1 || this.#better(a[k], a[m], min))) m = k;
      }
      if (m === -1 || !this.#better(a[m], a[i], min)) return;
      const grandchild = m >= 4*i+3;
      this.#swap(i, m);
      if (!grandchild) return;
      const p = Math.floor((m - 1) / 2);
      if (this.#better(a[p], a[m], min)) this.#swap(m, p);
      i = m; // Continue from the same-parity grandchild slot.
    }
  }
  #remove(i) {
    if (i < 0 || this.size === 0) return undefined;
    const value = this.#a[i];
    const last = this.#a.pop();
    if (i < this.size) {
      this.#a[i] = last;
      this.#down(i, i === 0);
    }
    return value;
  }
  popMin() { return this.#remove(0); }
  popMax() { return this.#remove(this.#maxIndex()); }
}
const assert = require("node:assert/strict");
const h = new MinMaxHeap();
h.push(2).push(-0).push(2);
let rejected = 0;
for (const bad of [NaN, Infinity, -Infinity, "2", null, undefined, 1n, {}, new Number(2)]) {
  const before = h.snapshot();
  assert.throws(() => h.push(bad), TypeError);
  assert.deepEqual(h.snapshot(), before);
  rejected++;
}
const detached = h.snapshot(); detached[0] = -1000;
assert.equal(h.getMin(), 0);
assert.equal(Object.is(h.getMin(), -0), false);
const extreme = new MinMaxHeap();
[-Number.MAX_VALUE, Number.MAX_VALUE, Number.MIN_VALUE].forEach(n => extreme.push(n));
assert.equal(extreme.popMin(), -Number.MAX_VALUE);
assert.equal(extreme.popMax(), Number.MAX_VALUE);
assert.equal(extreme.popMin(), Number.MIN_VALUE);
console.log(`rejected without mutation: ${rejected}`);
console.log("snapshot detached; -0 normalized; finite extremes: OK");

实际输出:

rejected without mutation: 9
snapshot detached; -0 normalized; finite extremes: OK

把审查落在可以被反驳的断言上

审查双端堆,不必追求一眼看起来最短的代码。先问输入是否形成明确的序,再问每一层承担什么约束,接着看插入何时跨父层、删除何时跨孙层,以及跨层后哪一条旧关系可能失效。最后让与堆结构无关的参考模型反复尝试推翻这些断言。

这份实现的关键不是同时拥有两个取值方法,而是在每次修改后仍让两端共享一份一致的多重集。相同优先级的数量、空队列语义、被拒绝输入的无副作用、孙节点交换后的父边修复,都是同一份合同的组成部分。把它们分别写成可运行测试,AI 生成的实现才真正变成可以审阅、可以复现、也可以指出反例的代码。

参考来源:Min-Max Heaps and Generalized Priority Queues 原论文;ECMAScript 的 Number.isFinite 定义;Node.js 严格断言文档。算法来源、本文实现与测试结论分别列明,文中的测试数字仅对应本次实际执行。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。