SortedSet
SortedSet<T> is an ordered set backed by a balanced binary search tree. It keeps every element in sorted order and ignores duplicate inserts. The native handle is released automatically when the binding goes out of scope.
Construction
| Syntax | Description |
|---|---|
SortedSet<T>() | Create a new empty ordered set |
T can be any integer type, any float type, boolean, or string.
Methods
| Method | Signature | Returns | Description |
|---|---|---|---|
insert | (T) => boolean | boolean | Add an element; returns true when it was not present |
remove | (T) => boolean | boolean | Remove an element; returns true when it was present |
contains | (T) => boolean | boolean | Whether the element is in the set |
min | () => T? | T? | Smallest element, or no value when empty |
max | () => T? | T? | Largest element, or no value when empty |
len | () => usize | usize | Number of elements |
isEmpty | () => boolean | boolean | Whether the set is empty |
clear | () => void | void | Remove all elements |
Complexity
| Operation | Time Complexity |
|---|---|
insert | O(log n) |
remove | O(log n) |
contains | O(log n) |
min / max | O(log n) |
len / isEmpty | O(1) |
clear | O(n) |
The tree stays balanced, so every lookup, insertion and deletion is logarithmic regardless of insertion order.
Examples
Complete example
tyrus
import { SortedSet } from "tyrus:algorithm";
const main = (): void => {
const s = SortedSet<i32>();
s.insert(3);
s.insert(1);
s.insert(2);
s.insert(2);
print(s.len()); // 3 (duplicates are ignored)
print(s.contains(2)); // true
print(s.min() ?? 0); // 1
print(s.max() ?? 0); // 3
s.remove(2);
print(s.contains(2)); // false
print(s.isEmpty()); // false
s.clear();
print(s.isEmpty()); // true
print(s.len()); // 0
};String ordering
tyrus
import { SortedSet } from "tyrus:algorithm";
const main = (): void => {
const words = SortedSet<string>();
words.insert("banana");
words.insert("apple");
words.insert("cherry");
print(words.min() ?? "none"); // "apple"
print(words.max() ?? "none"); // "cherry"
};