Skip to content
CryoCryo home
Stdlibcollections

binary_heap

import std::collections::binary_heap; · source

Types

BinaryHeap<T, A>

type struct BinaryHeap<T, A = GlobalAllocator> where A: Allocator {
    private elements: Array<T, A>;
}

A priority queue: pop hands out the greatest element first, by Ord. The elements are kept in an Array laid out as a max-heap — the element at index i is no less than those at 2i + 1 and 2i + 2 — so push and pop are O(log n) and peek is O(1).

import std::collections::binary_heap::{ BinaryHeap };

mut heap: BinaryHeap<i64> = BinaryHeap::new();
heap.push(3);
heap.push(9);
heap.push(4);
const largest: Option<i64> = heap.pop();   // Some(9)

from_array arranges an existing array into a heap in O(n), and into_sorted uses the heap up to hand back its elements in ascending order. For the smallest element first, order the elements the other way round with a wrapper whose Ord is reversed.

Constructors

static new() -> BinaryHeap<T, GlobalAllocator>;

An empty heap backed by GlobalAllocator.

static new_in(alloc: A) -> BinaryHeap<T, A>;

An empty heap that allocates through alloc.

static from_array(elements: Array<T, A>) -> BinaryHeap<T, A> where T: Ord;

A heap holding the elements of elements, arranged in O(n).

Methods

length(&this) -> i64;

The number of elements in the heap.

is_empty(&this) -> boolean;

True when the heap has no elements.

peek(&this) -> Option<T*>;

The greatest element, or None when empty.

push(mut &this, value: T) -> void where T: Ord;

Add value. Panics on allocation failure.

pop(mut &this) -> Option<T> where T: Ord;

Remove and return the greatest element, or None when empty.

into_sorted(mut this) -> Array<T, A> where T: Ord;

The elements in ascending order. The heap is used up.