Grav v1.14.0

PriorityQueue

import "std/collections" (included in import "std") · namespace std.collections

PriorityQueue<T> always hands out the "best" element next, where best is decided by a comparison function: the element for which cmp(a, b) < 0 comes first. It is a binary heap: push and pop are O(log n), peek is O(1). Use it for scheduling, "top N" problems and shortest-path algorithms.

grav
import "std"

class Job {
    public name: string
    public priority: int
    constructor(name: string, priority: int) { self.name = name; self.priority = priority }
}

fn main() {
    let smallest = new PriorityQueue<int>(fn(a, b) => a - b)
    for (n in [5, 1, 4, 2]) { smallest.push(n) }
    print(smallest.pop())
    print(smallest.peek())

    let jobs = new PriorityQueue<Job>(fn(a, b) => b.priority - a.priority)   // highest first
    jobs.push(new Job("backup", 1))
    jobs.push(new Job("outage", 10))
    jobs.push(new Job("email", 3))
    while (!jobs.isEmpty()) { print(jobs.pop().name) }
}
Output
1
2
outage
email
backup

pop and peek on an empty queue throw StateError. toArray() returns the elements in heap order, not sorted order.

API

class PriorityQueue<T>

Constructors

  • new PriorityQueue(cmp: fn(T, T) -> int)

Methods

  • fn push(item: T) — Adds an element (O(log n)).
  • fn pop() -> T — Removes and returns the first element by the comparator (StateError when empty).
  • fn peek() -> T — The first element by the comparator, left in place (StateError when empty).
  • fn size() -> int — The number of elements.
  • fn length() -> int — The number of elements (same as size()).
  • fn isEmpty() -> bool — Whether the queue is empty.
  • fn clear() — Removes every element.
  • fn contains(item: T) -> bool — Whether some element equals item.
  • fn toString() -> string — Every element, in priority order (the queue is left unchanged). As text: [1, 2, 3] (strings in quotes).
  • fn toArray() -> Array<T> — Every element, sorted by the comparator, as a new Array.

Edit this page on GitHub