Skip to content

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 ​

SyntaxDescription
SortedSet<T>()Create a new empty ordered set

T can be any integer type, any float type, boolean, or string.

Methods ​

MethodSignatureReturnsDescription
insert(T) => booleanbooleanAdd an element; returns true when it was not present
remove(T) => booleanbooleanRemove an element; returns true when it was present
contains(T) => booleanbooleanWhether 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() => usizeusizeNumber of elements
isEmpty() => booleanbooleanWhether the set is empty
clear() => voidvoidRemove all elements

Complexity ​

OperationTime Complexity
insertO(log n)
removeO(log n)
containsO(log n)
min / maxO(log n)
len / isEmptyO(1)
clearO(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"
};