SplMinHeap / SplMaxHeap

SplHeap(abstract)的现成子类,implements Iterator, Countable

抽象二叉堆的现成子类:SplMinHeap/SplMaxHeap 由 compare() 定堆序,insert/extract O(log n);迭代堆即出堆,遍历完堆空。

C C23

C23
#include <stdio.h>

/* C 反向对照:二叉堆在静态数组上手写
   (完全树:i 的父在 (i-1)/2,孩子在 2i+1 / 2i+2) */
static int heap[16] = {0}; /* 静态存储:零初始化 */
static int size = 0;

static void push(int v) {
    int i = size++;
    heap[i] = v;
    while (i > 0) {
        int p = (i - 1) / 2;
        if (heap[p] <= heap[i]) {
            break;
        }
        int t = heap[p];
        heap[p] = heap[i];
        heap[i] = t;
        i = p;
    }
}

static int pop(void) {
    int top = heap[0];
    heap[0] = heap[--size];
    int i = 0;
    for (;;) {
        int l = 2 * i + 1, r = l + 1, s = i;
        if (l < size && heap[l] < heap[s]) s = l;
        if (r < size && heap[r] < heap[s]) s = r;
        if (s == i) break;
        int t = heap[s];
        heap[s] = heap[i];
        heap[i] = t;
        i = s;
    }
    return top;
}

int main(void) {
    int data[] = {7, 2, 9, 4};
    for (int i = 0; i < 4; i++) {
        push(data[i]);
    }
    printf("min:");
    while (size > 0) {
        printf(" %d", pop());
    }
    printf("\n");
    return 0;
}
输出
min: 2 4 7 9

C++ C++26

C++26
#include <functional>
#include <iostream>
#include <queue>
#include <vector>

int main() {
    // C++ 反向对照:std::priority_queue 默认大顶堆;
    // 传 std::greater 翻转为小顶堆
    std::vector<int> data{7, 2, 9, 4};
    std::priority_queue<int> max(data.begin(), data.end());
    std::cout << "max:";
    while (!max.empty()) {
        std::cout << " " << max.top();
        max.pop();
    }
    std::cout << "\n";
    std::priority_queue<int, std::vector<int>, std::greater<int>> min(data.begin(), data.end());
    std::cout << "min:";
    while (!min.empty()) {
        std::cout << " " << min.top();
        min.pop();
    }
    std::cout << "\n";
    return 0;
}
输出
max: 9 7 4 2
min: 2 4 7 9

C# v11.0.100

v11.0.100
using System.Collections.Generic;

// C# 反向对照:PriorityQueue<TElement, TPriority> 收 (值, 优先级) 对,
// 按优先级小顶出队——值作自身优先级即「值堆」,取反即 max
var data = new[] { 7, 2, 9, 4 };
var min = new PriorityQueue<int, int>();
foreach (var n in data) min.Enqueue(n, n);
var mn = new List<int>();
while (min.Count > 0) mn.Add(min.Dequeue());
Console.WriteLine("min: " + string.Join(",", mn));
var max = new PriorityQueue<int, int>();
foreach (var n in data) max.Enqueue(n, -n);
var mx = new List<int>();
while (max.Count > 0) mx.Add(max.Dequeue());
Console.WriteLine("max: " + string.Join(",", mx));
输出
min: 2,4,7,9
max: 9,7,4,2

Go v1.27.4

v1.27.4
package main

import (
	"container/heap"
	"fmt"
)

// Go 反向对照:container/heap 是接口式设计——实现 sort.Interface
// 加 Push/Pop,堆逻辑由 heap.Init/Push/Pop 驱动
type MinHeap []int

func (h MinHeap) Len() int           { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h MinHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *MinHeap) Push(x any)        { *h = append(*h, x.(int)) }
func (h *MinHeap) Pop() any {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[:n-1]
	return x
}

type MaxHeap []int

func (h MaxHeap) Len() int           { return len(h) }
func (h MaxHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h MaxHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *MaxHeap) Push(x any)        { *h = append(*h, x.(int)) }
func (h *MaxHeap) Pop() any {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[:n-1]
	return x
}

func drain(h heap.Interface) []int {
	out := []int{}
	for h.Len() > 0 {
		out = append(out, heap.Pop(h).(int))
	}
	return out
}

func main() {
	minH := &MinHeap{7, 2, 9, 4}
	heap.Init(minH)
	fmt.Println("min:", drain(minH))
	maxH := &MaxHeap{7, 2, 9, 4}
	heap.Init(maxH)
	fmt.Println("max:", drain(maxH))
}
输出
min: [2 4 7 9]
max: [9 7 4 2]

Java v27.0.1

v27.0.1
import java.util.PriorityQueue;

public class Main {
    public static void main(String[] args) {
        // Java 反向对照:PriorityQueue 是二叉堆——默认小顶堆,
        // 反转比较器即大顶堆
        int[] data = {7, 2, 9, 4};
        PriorityQueue<Integer> min = new PriorityQueue<>();
        for (int n : data) min.add(n);
        StringBuilder mn = new StringBuilder();
        while (!min.isEmpty()) {
            if (mn.length() > 0) mn.append(",");
            mn.append(min.poll());
        }
        System.out.println("min: " + mn);
        PriorityQueue<Integer> max = new PriorityQueue<>((a, b) -> Integer.compare(b, a));
        for (int n : data) max.add(n);
        StringBuilder mx = new StringBuilder();
        while (!max.isEmpty()) {
            if (mx.length() > 0) mx.append(",");
            mx.append(max.poll());
        }
        System.out.println("max: " + mx);
    }
}
输出
min: 2,4,7,9
max: 9,7,4,2

JavaScript v26.13.1

v26.13.1
// JS 反向对照:无内建堆——在普通数组上手写一个
// (完全树,父节点在 (i-1)>>1)
class MinHeap {
  #a = [];
  get size() { return this.#a.length; }
  push(v) {
    this.#a.push(v);
    let i = this.#a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (this.#a[p] <= this.#a[i]) break;
      [this.#a[p], this.#a[i]] = [this.#a[i], this.#a[p]];
      i = p;
    }
  }
  pop() {
    const top = this.#a[0];
    const last = this.#a.pop();
    if (this.#a.length > 0) {
      this.#a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1, r = l + 1;
        let s = i;
        if (l < this.#a.length && this.#a[l] < this.#a[s]) s = l;
        if (r < this.#a.length && this.#a[r] < this.#a[s]) s = r;
        if (s === i) break;
        [this.#a[s], this.#a[i]] = [this.#a[i], this.#a[s]];
        i = s;
      }
    }
    return top;
  }
}
const h = new MinHeap();
for (const n of [7, 2, 9, 4]) h.push(n);
const out = [];
while (h.size > 0) out.push(h.pop());
console.log("min:", out.join(","));
输出
min: 2,4,7,9

PHP v8.6.0

v8.6.0
// SplHeap 是抽象类:子类实现 compare();SplMinHeap/SplMaxHeap
// 是两个现成实现(min 弹最小,max 弹最大)
$data = [7, 2, 9, 4];
$min = new SplMinHeap();
foreach ($data as $n) $min->insert($n);
$out = [];
while (!$min->isEmpty()) $out[] = $min->extract();
echo "min: ", implode(",", $out), "\n";
$max = new SplMaxHeap();
foreach ($data as $n) $max->insert($n);
$out = [];
while (!$max->isEmpty()) $out[] = $max->extract();
echo "max: ", implode(",", $out), "\n";
// 迭代堆即出堆:foreach 每步 extract 一次堆顶
$peek = new SplMaxHeap();
foreach ($data as $n) $peek->insert($n);
$drained = [];
foreach ($peek as $v) $drained[] = $v;
echo "iterate: ", implode(" ", $drained), "\n";
echo "after iterate count: ", $peek->count(), "\n";
输出
min: 2,4,7,9
max: 9,7,4,2
iterate: 9 7 4 2
after iterate count: 0

Python v3.15.2

v3.15.2
# Python 反向对照:heapq 是标准小顶堆;max 需求就是同一座堆
# 配负数键
import heapq

data = [7, 2, 9, 4]
h = data[:]
heapq.heapify(h) # 原地 O(n) 建堆
out = []
while h:
    out.append(heapq.heappop(h))
print("min:", ",".join(map(str, out)))

h2 = [-n for n in data]
heapq.heapify(h2)
out2 = [-heapq.heappop(h2) for _ in range(len(h2))]
print("max:", ",".join(map(str, out2)))
输出
min: 2,4,7,9
max: 9,7,4,2

Rust v1.99.1

v1.99.1
// Rust 反向对照:标准库自带 BinaryHeap——开箱即用的大顶堆;
// 元素包一层 Reverse 即小顶堆
use std::cmp::Reverse;
use std::collections::BinaryHeap;

fn main() {
    let mut max: BinaryHeap<i32> = vec![7, 2, 9, 4].into_iter().collect();
    let mut mx = vec![];
    while let Some(v) = max.pop() {
        mx.push(v);
    }
    println!("max: {:?}", mx);
    let mut min: BinaryHeap<Reverse<i32>> = vec![7, 2, 9, 4].into_iter().map(Reverse).collect();
    let mut mn = vec![];
    while let Some(Reverse(v)) = min.pop() {
        mn.push(v);
    }
    println!("min: {:?}", mn);
}
输出
max: [9, 7, 4, 2]
min: [2, 4, 7, 9]

TypeScript v26.13.1

v26.13.1
// TS 反向对照:无内建堆——手写一个;私有字段封装数组,
// 类型钉死元素种类
class MinHeap {
  #a: number[] = [];
  get size(): number { return this.#a.length; }
  push(v: number): void {
    this.#a.push(v);
    let i = this.#a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (this.#a[p] <= this.#a[i]) break;
      [this.#a[p], this.#a[i]] = [this.#a[i], this.#a[p]];
      i = p;
    }
  }
  pop(): number {
    const top = this.#a[0];
    const last = this.#a.pop() as number;
    if (this.#a.length > 0) {
      this.#a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1, r = l + 1;
        let s = i;
        if (l < this.#a.length && this.#a[l] < this.#a[s]) s = l;
        if (r < this.#a.length && this.#a[r] < this.#a[s]) s = r;
        if (s === i) break;
        [this.#a[s], this.#a[i]] = [this.#a[i], this.#a[s]];
        i = s;
      }
    }
    return top;
  }
}
const h = new MinHeap();
for (const n of [7, 2, 9, 4]) h.push(n);
const out: number[] = [];
while (h.size > 0) out.push(h.pop());
console.log("min:", out.join(","));
输出
min: 2,4,7,9

语言差异说明

C:无容器库——手写数组式二叉堆(示例:push 上浮 + pop 下沉),insert/extract 均 O(log n);static 数组零初始化兜底。

C++:std::priority_queue 默认大顶堆,传 std::greater 即小顶堆;底层容器可换,make_heap/push_heap/pop_heap 适合在自家容器上做堆操作。

C#:PriorityQueue<TElement, TPriority>(.NET 6+)按 priority 小顶出队——示例用值作自身优先级、取反实现 max;「值堆」要自己裹这层(值同时当优先级)。

Go:container/heap 是接口式设计——堆逻辑在库里,数据结构自己实现 sort.Interface + Push/Pop;min/max 只差一个 Less 方向。

Java:PriorityQueue 默认小顶堆,Comparator 反转即大顶;容量自动增长,批量初始化用 PriorityQueue(Collection)(内部 heapify,O(n))。

JavaScript:无内建堆——手写数组式二叉堆(示例);第三方库或「排序替代」是常见做法,后者 O(n log n) 但通常足够。

PHP:SplHeap 是抽象基类:子类实现 compare($a, $b)(负数=左优先)定堆序,SplMinHeap/SplMaxHeap 是两个现成实现;与 SplPriorityQueue 的分工——堆只存值(compare 定义全序),优先队列存 (数据, 优先级) 对。教学点:迭代堆即出堆——foreach 每步 extract,遍历完堆空(示例 count 归零),这与所有其他 SPL 容器的非破坏性迭代不同。

Python:heapq 是小顶堆(heapify O(n)、heappush/heappop O(log n));max 需求惯用负值技巧(示例),或包裹元组反转比较键。

Rust:std::collections::BinaryHeap 是标准库自带的大顶堆——PHP 要引 SPL 的场景,Rust 用 std 就够;min 需求用 Reverse 包装(示例)。

TypeScript:同 JS 手写堆;TS 的价值在把堆元素与比较器类型化(泛型 MinHeap 是练习泛型的经典教材)。