Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Priority Queue

PagedPriorityQueue<K, P, PAGE = 1024, D = Flat> is an indexed max-heap: keys map to priorities, the greatest priority comes out first, and a key’s priority can be changed or the key removed in O(log n). Use core::cmp::Reverse for a min-queue. Keys and priorities live in parallel contiguous arrays in heap order (a four-way heap); a paged index finds a key’s heap position.

Python: PriorityQueue (int64 priorities) and PriorityQueueF64 (float64); min=True makes either a min-queue. Pushing a present key changes its priority.

In a four-way max-heap, key 7 has the highest priority, 80. The paged index locates key 9 at heap position 2.
pop takes the root of the heap. Updating key 9 starts at position 2, and the entry moves if its new priority requires it.

Example

from paged_collections import PriorityQueue, PriorityQueueF64

queue = PriorityQueue()
for key, priority in [(7, 10), (2, 30), (9, 20), (4, 15)]:
    queue.push(key, priority)
# Pushing an existing key changes its priority and returns the old priority.
print("old priority =", queue.push(7, 40))
print("removed =", queue.remove(9))
print("pop order =", [queue.pop() for _ in range(len(queue))])

floats = PriorityQueueF64(min=True)
floats.push(7, 1.5)
floats.push(2, 0.5)
floats.push(9, 2.5)
floats.push(7, 0.25)
floats.remove(9)
print("float min order =", [floats.pop() for _ in range(len(floats))])
use paged_collections::priority_queue::PagedPriorityQueue;

fn main() {
    let mut queue: PagedPriorityQueue<usize, i32> = PagedPriorityQueue::new();
    for (key, priority) in [(7, 10), (2, 30), (9, 20), (4, 15)] {
        queue.push(key, priority);
    }
    println!("old priority = {}", queue.change_priority(&7, 40).unwrap());
    println!("removed = {}", queue.remove(&9).unwrap().1);
    let mut order = Vec::new();
    while let Some(item) = queue.pop() {
        order.push(item);
    }
    println!("pop order = {order:?}");
}

Python output:

old priority = 10
removed = 20
pop order = [(7, 40), (2, 30), (4, 15)]
float min order = [(7, 0.25), (2, 0.5)]

The Rust example prints the first three lines.

Complexity

OperationCost
push, pop, change_priority, removeO(log n) comparisons
peek, priority, contains_keyO(1)
into_sorted_vecO(n log n)

Equal priorities come out in unspecified order.

In Rust, try_reserve(additional) reserves room in both dense arrays. If capacity overflows or allocation fails, the queue keeps its entries, array addresses and capacity.

Generational Keys

A slot holds one key. push evicts another generation of the key’s slot; try_push refuses. Lookups check the whole key.

Panic Safety

If a priority comparison or a change_priority_with closure panics, every remaining entry stays findable and paired with its priority, but heap order may be broken: later pop and sorted results are unspecified. The same applies when a stored priority’s ordering changes through interior mutability. Neither causes undefined behaviour.

Rust and Python

RustPython
push(k, p) -> Option<P>push(k, p), q[k] = p
try_push
push_increase, push_decreasepush_increase(k, p), push_decrease(k, p)
pop(), peek()pop(), peek() (raise IndexError when empty)
change_priority(&k, p), change_priority_withpush(k, p), q[k] = p
priority(&k)q[k], get(k, default)
remove(&k)remove(k), del q[k]
into_sorted_vec, into_sorted_itersorted()
keys, priorities, key_slice, priority_slicekeys(), items()
reserve, try_reserve

Python push_increase and push_decrease insert an absent key or update its priority only when the new numeric value is strictly greater or strictly smaller, respectively. Both return whether the queue changed. With min=True, pop() selects the lowest priority and these methods keep their numeric meanings.

API: PagedPriorityQueue.