BinaryHeap
BinaryHeap<T> implements a binary max-heap priority queue implemented in the native runtime. Elements are stored in a contiguous array and ordered by value, with the largest element always at the top.
Construction
| Syntax | Description |
|---|---|
BinaryHeap<T>() | Create a new empty heap with default capacity |
The type parameter T determines the element type. T must be an ordered numeric type (i8–i128, u8–u128, f32, f64, or f128).
Methods
| Method | Signature | Returns | Description |
|---|---|---|---|
push | (T) => void | void | Insert an element |
pop | () => T? | T? | Remove and return the largest element, or empty if empty |
peek | () => T? | T? | Return the largest element without removing it, or empty if empty |
len | () => usize | usize | Number of elements |
isEmpty | () => boolean | boolean | Whether the heap has no elements |
clear | () => void | void | Remove all elements |
The native handle is released automatically when the binding goes out of scope.
Complexity
| Operation | Time Complexity |
|---|---|
push | O(log n) |
pop | O(log n) |
peek | O(1) |
len | O(1) |
isEmpty | O(1) |
clear | O(n) |
Examples
Construction
tyrus
import { BinaryHeap } from "tyrus:algorithm";
const bh = BinaryHeap<i32>();push
tyrus
const bh = BinaryHeap<i32>();
bh.push(10);
bh.push(3);
bh.push(7);
print(bh.len()); // 3pop
tyrus
const bh = BinaryHeap<i32>();
bh.push(10);
bh.push(3);
bh.push(7);
const p1: i32? = bh.pop();
if (p1) {
print(p1); // 10
}
const p2: i32? = bh.pop();
if (p2) {
print(p2); // 7
}
const p3: i32? = bh.pop();
if (p3) {
print(p3); // 3
}
const p4: i32? = bh.pop();
print(p4 ?? -1); // -1peek
tyrus
const bh = BinaryHeap<i32>();
bh.push(10);
bh.push(3);
const top: i32? = bh.peek();
if (top) {
print(top); // 10
}len
tyrus
const bh = BinaryHeap<i32>();
print(bh.len()); // 0
bh.push(5);
bh.push(1);
print(bh.len()); // 2isEmpty
tyrus
const bh = BinaryHeap<i32>();
print(bh.isEmpty()); // true
bh.push(1);
print(bh.isEmpty()); // falseclear
tyrus
const bh = BinaryHeap<i32>();
bh.push(10);
bh.push(3);
bh.push(7);
print(bh.len()); // 3
bh.clear();
print(bh.isEmpty()); // true
print(bh.len()); // 0