SplMinHeap / SplMaxHeap
SplHeap(abstract)的现成子类,implements Iterator, Countable
Ready-made subclasses of the abstract binary heap: SplMinHeap/SplMaxHeap order themselves via compare(), insert/extract O(log n); iterating a heap drains it.
C C23
#include <stdio.h>
/* C in reverse: the binary heap is hand-rolled on a static array
(complete tree: parent of i at (i-1)/2, children at 2i+1 / 2i+2) */
static int heap[16] = {0}; /* static storage: zero-initialized */
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
#include <functional>
#include <iostream>
#include <queue>
#include <vector>
int main() {
// C++ in reverse: std::priority_queue is a max-heap by default;
// std::greater flips it into a min-heap
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
using System.Collections.Generic;
// C# in reverse: PriorityQueue<TElement, TPriority> takes (value, priority)
// pairs and is a min-heap on the priority - use the value as its own
// priority, or negate it for a max-heap
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
package main
import (
"container/heap"
"fmt"
)
// Go in reverse: container/heap is interface-based - implement
// sort.Interface plus Push/Pop, then heap.Init/Push/Pop drive the array
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
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) {
// Java in reverse: PriorityQueue is the binary heap - a min-heap by
// default, a max-heap via a reversed comparator
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
// JS in reverse: no built-in heap - hand-write one on a plain array
// (complete tree, parent at (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
// SplHeap is abstract: subclass it and implement compare(); SplMinHeap/SplMaxHeap
// are the two ready-made heaps (min pops smallest, max pops largest)
$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";
// Iterating a heap IS draining it: each next() extracts the top
$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
# Python in reverse: heapq is the standard min-heap; a max-heap is the same
# heap over negated keys
import heapq
data = [7, 2, 9, 4]
h = data[:]
heapq.heapify(h) # O(n) heapify in place
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
// Rust in reverse: std ships BinaryHeap - a MAX-heap out of the box;
// wrap elements in Reverse for a min-heap
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
// TS in reverse: no built-in heap - hand-write one; private fields keep the
// array encapsulated, types pin the element kind
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
Language differences
C: no container library - hand-write the array-backed binary heap (shown: sift-up on push, sift-down on pop), insert/extract O(log n); a static array is zero-initialized for free.
C++: std::priority_queue is a max-heap by default; pass std::greater for min - the underlying container is swappable, and make_heap/push_heap/pop_heap do heap ops on your own containers.
C#: PriorityQueue<TElement, TPriority> (.NET 6+) dequeues the SMALLEST priority - the example uses each value as its own priority and negates for max; a plain value-heap needs the same wrap.
Go: container/heap is interface-based - heap logic lives in the library, the data structure implements sort.Interface + Push/Pop; min vs max is one Less direction.
Java: PriorityQueue is a min-heap by default, a reversed Comparator makes it max; capacity grows automatically, and bulk init via PriorityQueue(Collection) heapifies in O(n).
JavaScript: no built-in heap - hand-write the array-backed one (shown); a third-party lib or "sort instead" are the common routes, the latter O(n log n) but usually plenty.
PHP: SplHeap is an ABSTRACT base: subclasses implement compare($a, $b) (negative = left wins) and SplMinHeap/SplMaxHeap are the two ready-made implementations; the split with SplPriorityQueue - a heap stores values only (compare defines the total order), a priority queue stores (data, priority) pairs. Teaching point: ITERATING A HEAP DRAINS IT - each foreach step extracts, and the heap ends up empty (count 0 in the example), unlike every other SPL container's non-destructive iteration.
Python: heapq is a min-heap (heapify O(n), heappush/heappop O(log n)); max needs are the classic negative-value trick (shown), or wrapped tuples with inverted compare keys.
Rust: std::collections::BinaryHeap is a MAX-heap in the standard library - where PHP reaches for SPL, Rust covers it with std; min needs get the Reverse wrapper (shown).
TypeScript: the same hand-written heap as JS; TS's value is typing the element and comparator (a generic MinHeap is the classic generics exercise).